首先是屏幕截图, 参数rectangle 需要传进去需要截图的矩形坐标
/// <summary>
/// 屏幕截图
/// </summary>
/// <param name="rectangle">矩形坐标</param>
public Bitmap Screenshoot(Rectangle rectangle)
{
try
{
int sourceX = rectangle.Location.X;
int sourceY = rectangle.Location.Y;
int destinationX = rectangle.Width;
int destinationY = rectangle.Height;
Bitmap bitmap = new Bitmap(rectangle.Width, rectangle.Height);
using (Graphics g = Graphics.FromImage(bitmap))
{
g.CopyFromScreen(sourceX, sourceY, 0, 0, bitmap.Size);
g.Dispose();
}
return bitmap;
}
catch (Exception)
{
throw;
}
}
需要把截图下来的图片转为HObject类型
public void Bitmap2HObject(Bitmap bmp, out HObject image)
{
try
{
Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
BitmapData srcBmpData = bmp.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
HOperatorSet.GenImageInterleaved(out image, srcBmpData.Scan0, "bgr", bmp.Width, bmp.Height, 0, "byte", 0, 0, 0, 0, -1, 0);
bmp.UnlockBits(srcBmpData);
}
catch (Exception ex) { image = null; }
}
最后是基于Halcon识别图片,需要安装Halcon导入halcondotnet.dll
Universal_0-9A-Z_Rej.occ 是Halcon自带的识别库,在Halcon的安装目录下可以找到,然后拷贝到自己的项目目录下使用
/// <summary>
/// 识别图片基于Halcon库
/// </summary>
public string HalconScanImage()
{
try
{
string ocrpath = AppDomain.CurrentDomain.BaseDirectory + "\\ocr\\Universal_0-9A-Z_Rej.occ";
HTuple hv_TextResultID = null; HTuple resultValue = null; HTuple hv_TextModel = null;
HObject ho_Image;
HOperatorSet.GenEmptyObj(out ho_Image);
//HOperatorSet.ReadImage(out ho_Image, filename);
Bitmap2HObject(Screenshoot(new Rectangle(1, 1, 20, 50)),out ho_Image);
HOperatorSet.CreateTextModelReader("auto", ocrpath , out hv_TextModel);
HOperatorSet.SetTextModelParam(hv_TextModel, "max_char_height", 18);
HOperatorSet.SetTextModelParam(hv_TextModel, "max_char_width", 10);
HOperatorSet.FindText(ho_Image, hv_TextModel, out hv_TextResultID);
HOperatorSet.GetTextResult(hv_TextResultID, "class", out resultValue); //获取测试结果
//todo halcon 解析图片结果
string resultStr = string.Empty;
if (resultValue.Length == 0) resultStr = "";
else
{
foreach (var item in resultValue.SArr)
{
resultStr += item;
}
}
return resultStr;
}
catch (Exception)
{
throw;
}
}