Skip to main content
 首页 » 编程设计

c#之从图像中获取点的坐标

2024年02月13日16虾米哥

我正在创建一个程序,可以从某个像素打印出 x 和 y 坐标。有一个像“GetPixel”这样的函数,但是这将从给定坐标获取 RGB 代码。我想要的只是反之亦然,所以我已经有了 RGB 代码,现在我正在通过我的图像做一个阈值,以了解它是否包含我想要的颜色像素。

这是我的代码:

所以首先我要上传一张图片:

    public BitmapImage bitmap; 
 
    public void hochladen_Click(object sender, EventArgs e) 
    { 
        // Create OpenFileDialog  
        Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog(); 
 
        // Set filter for file extension and default file extension  
        dlg.DefaultExt = ".bmp"; 
        dlg.Filter = "BMP Files (*.bmp)|*.bmp"; 
 
        // Get the selected file name and display in a TextBox  
        if (dlg.ShowDialog() == true) 
       {  
            // Open document  
            string filename = dlg.FileName; 
            bitmap = new BitmapImage(); 
            bitmap.BeginInit(); 
            bitmap.UriSource = new Uri(filename); 
            bitmap.EndInit(); 
            image.Source = bitmap; 
        } 
    } 

然后,当我在我的应用程序中单击一个按钮时,它应该根据我的图像做一个阈值,我将检测一个红色点(R = 255,G = B = 0)

    public Color c; 
 
    private void detektieren_Click(object sender, RoutedEventArgs e) 
    { 
        double x = bitmap.Width; 
        double y = bitmap.Height; 
        bl.Content = x + "x" + y; 

所以从这个点开始,应该不难找到坐标了:

        for (int i = 0; i < x; i++) 
        { 
            for (int j = 0; i < j; j++) 
            { 
                if (c.R == 255 && c.G == 0 && c.B == 0) 
                { 
                    // 
                } 
            } 
        } 
    } 

有人知道吗?提前致谢。

请您参考如下方法:

寻找匹配一个RGB值的像素当然可能会返回很多像素,试试下面的代码来获取Point结构表示的所有像素:

public Point[] GetPixelsFromRGB(byte[] rgbData, int stride, Color colorToFind){ 
  int k = stride/4; 
  return rgbData.Select((x,i)=>new{x,i}) 
                .GroupBy(a=>a.i/4,(key,a)=>a.ToArray()) 
                .Where(g=>g[0].x == colorToFind.Red && 
                          g[1].x == colorToFind.Green && 
                          g[2].x == colorToFind.Blue && g[3].x == 255) 
                .Select(g=> new Point(g[0].i%k, g[0].i / k)).ToArray(); 
} 
//Use this method to get the rgbData 
int stride = bitmap.PixelWidth * 4; 
byte[] rgbData = new byte[stride * bitmap.PixelHeight]; 
bitmap.CopyPixels(rgbData, stride, 0); 
//then call the method above: 
var pixels = GetPixelsFromRGB(rgbData, stride, Colors.Red); 

请注意,上面的代码没有经过测试,我只是直接在答案编辑器中输入。