如何在C#中获取600x400扫描图中3个黑点的(X,Y)坐标
在C#中获取扫描图像黑点坐标的简便方案
你提到有一张600x400px的扫描图像(如下所示),里面包含3个黑点,想要用C#快速获取它们的坐标,并且输出指定格式的结果。我给你整理了一个基于.NET原生System.Drawing库的简单方法,不需要额外依赖,步骤清晰易上手:

实现思路
核心逻辑就是加载图像后遍历每个像素,判断颜色是否为黑点(考虑到扫描可能有轻微噪点,我们可以设置一个颜色阈值,当RGB三个通道的值都低于某个数值时,就判定为黑点),最后收集坐标并按要求格式输出。
完整代码示例
using System; using System.Collections.Generic; using System.Drawing; class DotCoordinateDetector { static void Main() { // 替换为你的图像路径 string imagePath = "your-image-path.png"; // 颜色阈值:RGB都低于这个值就判定为黑点(可根据实际调整) int blackThreshold = 50; // 存储黑点坐标(去重,避免同一个黑点的多个像素被重复记录) HashSet<Tuple<int, int>> dotCoordinates = new HashSet<Tuple<int, int>>(); using (Bitmap bitmap = new Bitmap(imagePath)) { // 遍历图像的每个像素 for (int y = 0; y < bitmap.Height; y++) { for (int x = 0; x < bitmap.Width; x++) { Color pixelColor = bitmap.GetPixel(x, y); // 判断是否为黑点 if (pixelColor.R < blackThreshold && pixelColor.G < blackThreshold && pixelColor.B < blackThreshold) { // 检查相邻像素,避免重复记录同一个黑点 bool isNewDot = true; if (dotCoordinates.Contains(Tuple.Create(x - 1, y)) || dotCoordinates.Contains(Tuple.Create(x + 1, y)) || dotCoordinates.Contains(Tuple.Create(x, y - 1)) || dotCoordinates.Contains(Tuple.Create(x, y + 1))) { isNewDot = false; } if (isNewDot) { dotCoordinates.Add(Tuple.Create(x, y)); } } } } } // 按要求格式输出结果 int dotIndex = 1; string output = ""; foreach (var coord in dotCoordinates) { output += $"dot{dotIndex} X={coord.Item1}px Y={coord.Item2}px "; dotIndex++; } output = output.TrimEnd(); Console.WriteLine(output); // 预期输出示例:dot1 X=400px Y=100px dot2 X=100px Y=200px dot3 X=300px Y=300px } }
关键说明
- 颜色阈值:
blackThreshold可以根据你的扫描图实际情况调整,如果黑点非常黑,设为20左右也可以;如果有轻微灰噪点,调高到50-80能过滤掉干扰。 - 去重逻辑:代码里通过检查相邻像素避免重复记录同一个黑点的多个像素,确保每个黑点只记录一个坐标(当前取黑点左上角的像素,你也可以改成取中心像素,调整判断逻辑即可)。
- 环境注意:如果是.NET Core/.NET 5+项目,需要安装
System.Drawing.CommonNuGet包才能使用Bitmap类;.NET Framework项目直接引用即可。
内容的提问来源于stack exchange,提问作者CrownFord
相关产品推荐
相关产品推荐

