C#中Bitmap对象原点(0,0)位置约定及指定区域像素遍历问题
C# Bitmap类的原点位置说明及裁剪区域遍历建议
Josh,咱们直接说重点:在C#的System.Drawing.Bitmap类里,原点(0,0)固定在图像的左上角,坐标轴的排布规则是:
- x轴从左向右递增,数值越大越靠近图像右侧
- y轴从上向下递增,数值越大越靠近图像底部
你现在写的CountPixels函数完全符合这个坐标规则——从顶部(y=0)到底部,从左侧(x=0)到右侧遍历所有像素,逻辑是完全正确的。
针对你需要分析四边各裁剪5%的区域的需求,我帮你梳理下这个区域的坐标计算方式:
假设原图像宽为bm.Width,高为bm.Height:
- 水平方向的裁剪边距 = 图像宽度 × 0.05
- 垂直方向的裁剪边距 = 图像高度 × 0.05
- 裁剪后区域的起始x坐标 = 水平边距(取整)
- 裁剪后区域的起始y坐标 = 垂直边距(取整)
- 裁剪后区域的宽度 = 原宽度 - 2×水平边距
- 裁剪后区域的高度 = 原高度 - 2×垂直边距
基于这个计算,你可以修改遍历函数,只处理目标区域,代码示例如下:
ulong CountPixelsInCroppedArea(Bitmap bm, Color target_color) { ulong matches = 0; float cropPercent = 0.05f; int horizontalMargin = (int)Math.Round(bm.Width * cropPercent); int verticalMargin = (int)Math.Round(bm.Height * cropPercent); // 确定裁剪区域的边界 int startX = horizontalMargin; int startY = verticalMargin; int endX = bm.Width - horizontalMargin; int endY = bm.Height - verticalMargin; // 遍历裁剪后的区域 for (int y = startY; y < endY; y++) { for (int x = startX; x < endX; x++) { if (bm.GetPixel(x, y) == target_color) { matches++; } } } return matches; }
既然你提到图像体积不大,GetPixel的性能完全够用,这个修改后的函数就足够满足你的需求,不用折腾更复杂的高效方法。
内容的提问来源于stack exchange,提问作者Josh.h
相关产品推荐
相关产品推荐

