要实现 C# 识别图片并用鼠标点击图片的功能,您需要使用图像处理库,例如 Emgu CV 或 OpenCV。以下是基本的步骤:

  1. 加载要识别的图像。
  2. 使用图像处理算法(如模板匹配)识别图像中的目标区域。
  3. 使用 C# 的鼠标控制库(如 Windows.Forms.Mouse 类)模拟鼠标点击事件。

下面是一个简单的示例代码:

using System;
using System.Drawing;
using System.Windows.Forms;
using Emgu.CV;
using Emgu.CV.Structure;

namespace ImageRecognition
{
    public partial class Form1 : Form
    {
        private Image<Bgr, byte> targetImage;

        public Form1()
        {
            InitializeComponent();
        }

        private void loadImageButton_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                targetImage = new Image<Bgr, byte>(openFileDialog.FileName);
                targetPictureBox.Image = targetImage.Bitmap;
            }
        }

        private void recognizeImageButton_Click(object sender, EventArgs e)
        {
            Image<Bgr, byte> screenshot = new Image<Bgr, byte>(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
            Graphics graphics = Graphics.FromImage(screenshot.Bitmap);
            graphics.CopyFromScreen(Point.Empty, Point.Empty, Screen.PrimaryScreen.Bounds.Size);

            using (Image<Bgr, byte> resultImage = screenshot.MatchTemplate(targetImage, TemplateMatchingType.CcoeffNormed))
            {
                double[] minValues, maxValues;
                Point[] minLocations, maxLocations;
                resultImage.MinMax(out minValues, out maxValues, out minLocations, out maxLocations);

                if (maxValues[0] > 0.9)
                {
                    Point targetLocation = maxLocations[0];
                    Cursor.Position = new Point(targetLocation.X + targetImage.Width / 2, targetLocation.Y + targetImage.Height / 2);
                    Mouse.LeftClick();
                }
            }
        }
    }
}

在这个示例中,我们使用了 Emgu CV 库来加载和处理图像。首先,用户通过点击'Load Image'按钮选择要识别的图像。然后,当用户点击'Recognize Image'按钮时,我们获取当前屏幕的截图,并使用模板匹配算法来查找目标图像在屏幕上的位置。如果找到了匹配的位置,则将鼠标移动到该位置并模拟鼠标左键点击事件。请注意,我们使用了 Windows.Forms.Mouse 类中的 Mouse.LeftClick() 方法来模拟鼠标点击事件。

请注意,这只是一个简单的示例代码,并且可能需要根据您的实际需求进行修改。例如,您可能需要添加一些错误处理代码来处理无法加载图像或无法找到匹配位置的情况。

C# 图片识别与鼠标点击:自动点击目标图像

原文地址: https://www.cveoy.top/t/topic/ol6g 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录