TFLH/ViewModel/Vision/V_OcrVM.cs
2026-08-06 09:50:46 +08:00

698 lines
25 KiB
C#

using HalconDotNet;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Model;
using Community;
using System.Windows;
using System.IO;
using System.Collections.ObjectModel;
using Model.Vision;
namespace ViewModel.Vision
{
/// <summary>
/// OCR_VM
/// </summary>
partial class HalconVisual
{
#region 各种方法
/// <summary>
/// 创建图像校正模型
/// </summary>
public DelegateCommand CreateImageCorrectionModelCommand { get; set; }
/// <summary>
/// 图像校正测试
/// </summary>
public DelegateCommand ImageCorrectionTestCommand { get; set; }
/// <summary>
/// 新增OCR roi
/// </summary>
public DelegateCommand AddOcrRoiCommand { get; set; }
/// <summary>
/// 保存OCR roi
/// </summary>
public DelegateCommand SaveOcrRoiCommand { get; set; }
/// <summary>
/// 字体训练
/// </summary>
public DelegateCommand FontTrainingCommand { get; set; }
/// <summary>
/// OCR字符读取识别测试
/// </summary>
public DelegateCommand OcrReadTestCommand { get; set; }
#endregion
#region 校正后的图像
/// <summary>
/// 校正后的图像
/// </summary>
HObject CorrectingImage;
#endregion
#region 选中的Ocr ROI
private V_ROI selectOcrRoi;
/// <summary>
/// 选中的Ocr ROI
/// </summary>
public V_ROI SelectOcrRoi
{
get { return selectOcrRoi; }
set
{
selectOcrRoi = value;
this.RaisePropertyChanged("SelectOcrRoi");
}
}
#endregion
#region OCR相关初始化
/// <summary>
/// OCR相关初始化
/// </summary>
public void V_OcrVMInitialization()
{
CreateImageCorrectionModelCommand = new DelegateCommand();
CreateImageCorrectionModelCommand.ExecuteAction = new Action<object>(CreateImageCorrectionModel);
ImageCorrectionTestCommand = new DelegateCommand();
ImageCorrectionTestCommand.ExecuteAction = new Action<object>(ImageCorrectionTest);
AddOcrRoiCommand = new DelegateCommand();
AddOcrRoiCommand.ExecuteAction = new Action<object>(AddOcrRoi);
SaveOcrRoiCommand = new DelegateCommand();
SaveOcrRoiCommand.ExecuteAction = new Action<object>(SaveOcrRoi);
FontTrainingCommand = new DelegateCommand();
FontTrainingCommand.ExecuteAction = new Action<object>(FontTraining);
OcrReadTestCommand = new DelegateCommand();
OcrReadTestCommand.ExecuteAction = new Action<object>(OcrReadTest);
}
#endregion
#region 保存字符识别ROI
/// <summary>
/// 保存字符识别ROI
/// </summary>
/// <param name="obj"></param>
private void SaveOcrRoi(object obj)
{
if (SelectOcrRoi != null)
{
if (SelectOcrRoi.ID > 0)
{
if (Vdal.UpdateROI(SelectOcrRoi) <= 0)
{
MessageBox.Show("保存失败");
}
}
else
{
if (Vdal.AddRectangleROI(SelectOcrRoi) > 0)
{
SelectModel.MyRoiList = Vdal.GetROIList(SelectModel.ID, SelectOcrRoi.ROIType);
SelectVEI.MyRectangleModel.MyRoiList = SelectModel.MyRoiList;
}
else
{
MessageBox.Show("保存失败");
}
}
}
}
#endregion
#region 新增字符识别ROI
/// <summary>
/// 新增字符识别ROI
/// </summary>
/// <param name="obj"></param>
private void AddOcrRoi(object obj)
{
if (SelectModel.ID <= 0)
{
if (SaveAll(SelectModel))
{
SelectModel = Vdal.GetRectangleModel(SelectModel.VeiID, SelectModel.AreaType);
if (SelectModel.ID > 0)
{
SelectModel.MyRoiList.Add(new V_ROI() { ModelID = SelectModel.ID, ROIType = 2, Notes = "请输入识别的字符" });
}
else
{
MessageBox.Show("数据读取错误");
}
}
}
else
{
SelectModel.MyRoiList.Add(new V_ROI() { ModelID = SelectModel.ID, ROIType = 2, Notes = "请输入识别的字符" });
}
}
#endregion
#region 创建图像校正模型
/// <summary>
/// 创建图像校正模型
/// </summary>
/// <param name="obj"></param>
private void CreateImageCorrectionModel(object obj)
{
if (SelectVEI.ImageCorrectionRM.ID <= 0)
{
if (SaveAll(SelectVEI.ImageCorrectionRM))
{
SelectVEI.ImageCorrectionRM = Vdal.GetRectangleModel(SelectVEI.ImageCorrectionRM.VeiID, SelectVEI.ImageCorrectionRM.AreaType);
if (SelectVEI.ImageCorrectionRM.ID > 0)
{
GenerateFeaturesModel(SelectVEI.ImageCorrectionRM);
}
else
{
MessageBox.Show("数据读取错误");
}
}
}
else
{
GenerateFeaturesModel(SelectVEI.ImageCorrectionRM);
}
}
#endregion
#region 图像校正测试
/// <summary>
/// 图像校正测试
/// </summary>
/// <param name="obj"></param>
private void ImageCorrectionTest(object obj)
{
if (SelectVEI.ImageCorrectionRM.ID>0)
{
//1,获取图像
if (!GetImage())
{
return ;
}
ImageCorrecting(Ho_Image, SelectVEI.ImageCorrectionRM);
}
}
#endregion
#region 图像校正
/// <summary>
/// 图像校正
/// </summary>
public bool ImageCorrecting(HObject Image, V_RectangleModel RM)
{
bool pipeiOK = false;
// SetLight(RM);//设置光源亮度
HObject ho_ImageReduced, ho_ModelContours, ho_TransContours, ho_RectifiedImage = null;
HTuple hv_AlignmentHomMat2D = new HTuple();
HTuple hv_Row = new HTuple();
HTuple hv_Column = new HTuple(), hv_Angle = new HTuple();
HTuple hv_Score = new HTuple(), hv_RectificationHomMat2D = new HTuple();
HOperatorSet.GenEmptyObj(out ho_ImageReduced);
HOperatorSet.GenEmptyObj(out ho_ModelContours);
HOperatorSet.GenEmptyObj(out ho_TransContours);
HOperatorSet.GenEmptyObj(out ho_RectifiedImage);
try
{
if (!RM.MyROI.ReadFeatureModel())
{
ShowTextPer("读取特征模型文件失败", "red");
return pipeiOK;
}
RM.Instantiation();
//截取矩形选框中的图像
HOperatorSet.ReduceDomain(Image, RM.ho_RectangleModel, out ho_ImageReduced);
//识别图像特征
HOperatorSet.FindShapeModel(ho_ImageReduced, RM.MyROI.hv_ModelID, (new HTuple(0)).TupleRad(), (new HTuple(360)).TupleRad(), RM.MyROI.RecognitionCoefficient, 1, 0.5, (new HTuple("least_squares")).TupleConcat("max_deformation 5"), 0, 0.9, out hv_Row, out hv_Column, out hv_Angle, out hv_Score);
if (hv_Score == null || hv_Score.TupleLength() <= 0)
{
ShowTextPer("图像校正时,没有找到匹配的特征", "red");
return pipeiOK;
}
else
{
#region 在实际生产中这部分代码不需要显示
//模型将它转换成图像的轮廓
//HOperatorSet.GetShapeModelContours(out ho_ModelContours, RM.MyROI.hv_ModelID, 1);
//for (int i = 0; i <= hv_Score.TupleLength() - 1; i++)
//{
// HOperatorSet.HomMat2dIdentity(out hv_HomMat2D);
// HOperatorSet.HomMat2dRotate(hv_HomMat2D, hv_Angle.TupleSelect(i), 0, 0, out hv_HomMat2D);
// HOperatorSet.HomMat2dTranslate(hv_HomMat2D, hv_Row.TupleSelect(i), hv_Column.TupleSelect(i), out hv_HomMat2D);
// HOperatorSet.AffineTransContourXld(ho_ModelContours, out ho_TransContours, hv_HomMat2D);
//}
//for (int i = 0; i <= hv_Score.TupleLength() - 1; i++)
//{
// HOperatorSet.HomMat2dIdentity(out hv_AlignmentHomMat2D);
// //HOperatorSet.HomMat2dTranslate(hv_AlignmentHomMat2D, -hv_RefRow, -hv_RefColumn, out hv_AlignmentHomMat2D);
// HOperatorSet.HomMat2dTranslate(hv_AlignmentHomMat2D, -RM.MyROI.ModelFeaturePiont.hv_RefRow, -RM.MyROI.ModelFeaturePiont.hv_RefColumn, out hv_AlignmentHomMat2D);
// HOperatorSet.HomMat2dRotate(hv_AlignmentHomMat2D, hv_Angle.TupleSelect(i), 0, 0, out hv_AlignmentHomMat2D);
// HOperatorSet.HomMat2dTranslate(hv_AlignmentHomMat2D, hv_Row.TupleSelect(i), hv_Column.TupleSelect(i), out hv_AlignmentHomMat2D);
// //Matching 01: Insert your code using the alignment here, e.g. code generated by
// //Matching 01: the measure assistant with the code generation option
// //Matching 01: 'Alignment Method' set to 'Affine Transformation'.
//}
#endregion
for (int i = 0; i <= hv_Score.TupleLength() - 1; i++)
{
HOperatorSet.HomMat2dIdentity(out hv_RectificationHomMat2D);
HOperatorSet.HomMat2dTranslate(hv_RectificationHomMat2D, RM.MyROI.ModelFeaturePiont.hv_RefRow - (hv_Row.TupleSelect(i)), RM.MyROI.ModelFeaturePiont.hv_RefColumn - (hv_Column.TupleSelect(i)), out hv_RectificationHomMat2D);
HOperatorSet.HomMat2dRotate(hv_RectificationHomMat2D, -(hv_Angle.TupleSelect(i)), RM.MyROI.ModelFeaturePiont.hv_RefRow, RM.MyROI.ModelFeaturePiont.hv_RefColumn, out hv_RectificationHomMat2D);
ho_RectifiedImage.Dispose();
HOperatorSet.AffineTransImage(ho_Image, out ho_RectifiedImage, hv_RectificationHomMat2D, "constant", "false");
CorrectingImage = ho_RectifiedImage;
Ho_Image = CorrectingImage;
ShowObj(ho_RectifiedImage, "green");
}
pipeiOK = true;
}
}
catch (Exception)
{
ShowTextPer("图像校正失败","red");
}
return pipeiOK;
}
#endregion
#region 字体训练测试
/// <summary>
/// 字体训练测试
/// </summary>
/// <param name="obj"></param>
private void FontTraining(object obj)
{
OCRFontTraining(SelectVEI.ImageCorrectionRM, SelectOcrRoi);
}
#endregion
#region OCR字体训练
/// <summary>
/// OCR字体训练
/// </summary>
/// <param name="RM">区域对象(用于图像校正)</param>
/// <param name="roi"></param>
public void OCRFontTraining(V_RectangleModel RM, V_ROI roi)
{
if (RM == null || roi == null)
{
MessageBox.Show("OCR识别对象不能为空");
return;
}
if (roi.ID <= 0)
{
MessageBox.Show("请先保存当前选中的OCR");
return;
}
//1,获取图像
if (!GetImage())
{
return ;
}
if (!ImageCorrecting(Ho_Image, RM))
{
HOperatorSet.WriteString(HWindowWPF.HalconWindow, "图像校正失败");
return;
}
HObject ho_Rectangle, ho_Mono;
HObject ho_MonoReduced_OCR;
HObject ho_Symbols_OCR, ho_testRegion = null;
HTuple hv_TextModel = null;
HTuple hv_ResultHandle_OCR = null;
HTuple hv_Number = null, hv_ClassNames1 = null;
HTuple hv_OcrHandle = null, hv_Error = null;
HTuple hv_ErrorLog = null;
HTuple hv_Class = new HTuple(), hv_Confidence = new HTuple();
HTuple hv_Area = new HTuple(), hv_Row = new HTuple(), hv_Column = new HTuple();
// Initialize local and output iconic variables
HOperatorSet.GenEmptyObj(out ho_Rectangle);
HOperatorSet.GenEmptyObj(out ho_Mono);
HOperatorSet.GenEmptyObj(out ho_MonoReduced_OCR);
HOperatorSet.GenEmptyObj(out ho_Symbols_OCR);
HOperatorSet.GenEmptyObj(out ho_testRegion);
try
{
#region 训练识别
string AutoOcrFile = @"OCR/Industrial_Rej.omc";
// HOperatorSet.CreateTextModelReader("auto", AutoOcrFile, out hv_TextModel); //使用自动模式创建文字模型,次模式需要读取已有的OMC分类器文件
HOperatorSet.CreateTextModelReader("manual", new HTuple(), out hv_TextModel);
HOperatorSet.SetTextModelParam(hv_TextModel, "manual_char_width", 44); //符号宽度
HOperatorSet.SetTextModelParam(hv_TextModel, "manual_char_height", 50);//符号高度
HOperatorSet.SetTextModelParam(hv_TextModel, "manual_stroke_width", 18); //笔画宽度
HOperatorSet.SetTextModelParam(hv_TextModel, "manual_fragment_size_min", 5); //最小尺寸片段
HOperatorSet.SetTextModelParam(hv_TextModel, "manual_eliminate_border_blobs", "true"); //背景有纹理 比较复杂
HOperatorSet.SetTextModelParam(hv_TextModel, "manual_base_line_tolerance", 0.2);//基线公差
HOperatorSet.SetTextModelParam(hv_TextModel, "manual_max_line_num", 2); //文本行的最大行,需要识别的字符文本行有多少行
HOperatorSet.ReadOcrClassMlp(AutoOcrFile, out hv_OcrHandle); //获取分类模型
ClearWindowAndData();
ShowObj(CorrectingImage);
DrawROI(roi);
ho_Mono.Dispose();
HOperatorSet.AccessChannel(CorrectingImage, out ho_Mono, 1);
ho_MonoReduced_OCR.Dispose();
HOperatorSet.ReduceDomain(ho_Mono, roi.ho_OutlineROI, out ho_MonoReduced_OCR);
//寻找文本
HOperatorSet.FindText(ho_MonoReduced_OCR, hv_TextModel, out hv_ResultHandle_OCR);
ho_Symbols_OCR.Dispose();
HOperatorSet.GetTextObject(out ho_Symbols_OCR, hv_ResultHandle_OCR, "all_lines");
HOperatorSet.CountObj(ho_Symbols_OCR, out hv_Number);
ClearWindowAndData();
ShowObj(ho_MonoReduced_OCR);
SetDraw("fill");
SetColored(12);
ShowObj(ho_Symbols_OCR);
if (hv_Number != roi.Notes.Trim().Count())
{
ShowText("特征数量不等于预设字符数量", "red");
return;
}
HOperatorSet.DoOcrMultiClassMlp(ho_Symbols_OCR, ho_MonoReduced_OCR, hv_OcrHandle, out hv_Class, out hv_Confidence);
for (int i = 1; i <= hv_Number; i++)
{
HOperatorSet.SelectObj(ho_Symbols_OCR, out ho_testRegion, i);
HOperatorSet.AreaCenter(ho_testRegion, out hv_Area, out hv_Row, out hv_Column);
ShowText(hv_Class[i - 1], hv_Row + 50, hv_Column, "green");
}
if (hv_Class.ToString() != roi.Notes.Trim())
{
if (MessageBox.Show("训练识别到的字符与预设的字符不一致,是否继续", "提示", MessageBoxButton.YesNo) != MessageBoxResult.Yes)
{
return;
}
}
#endregion
#region 保存训练文件
hv_ClassNames1 = new HTuple();
//hv_ClassNames1[0] = "M";
//hv_ClassNames1[1] = "e";
//hv_ClassNames1[2] = "s";
//hv_ClassNames1[3] = "s";
//hv_ClassNames1[4] = "i";
//hv_ClassNames1[5] = "S";
//hv_ClassNames1[6] = "h";
//hv_ClassNames1[7] = "i";
int count = 0;
foreach (char s in roi.Notes.Trim())
{
hv_ClassNames1[count] = s.ToString();
count++;
}
//存储训练文件
if (!roi.AccessOcrTrainModel(ho_Symbols_OCR, ho_MonoReduced_OCR, hv_ClassNames1))
{
ShowText("存取训练文件失败", "red");
return;
}
//创建神经网络分类器mlp
HOperatorSet.CreateOcrClassMlp(8, 10, "constant", (new HTuple("pixel_invar")).TupleConcat("ratio"), roi.hv_CharacterNames, 42, "none", 10, 42, out hv_OcrHandle);
//训练
HOperatorSet.TrainfOcrClassMlp(hv_OcrHandle, roi.TrainFilePath, 200, 1, 0.01, out hv_Error, out hv_ErrorLog);
if (!roi.SaveOcrClassMlp(hv_OcrHandle))
{
ShowText("OCR分类器保存失败", "red");
return;
}
//清空窗体显示
ClearWindowAndData();
ShowObj(CorrectingImage);
ShowObj(ho_MonoReduced_OCR);
HOperatorSet.SetDraw(HWindowWPF.HalconWindow, "fill");
HOperatorSet.SetColored(HWindowWPF.HalconWindow, 12);
ShowObj(ho_Symbols_OCR);
HOperatorSet.DoOcrMultiClassMlp(ho_Symbols_OCR, ho_MonoReduced_OCR, hv_OcrHandle, out hv_Class, out hv_Confidence);
for (int i = 1; i <= hv_Number; i++)
{
HOperatorSet.SelectObj(ho_Symbols_OCR, out ho_testRegion, i);
HOperatorSet.AreaCenter(ho_testRegion, out hv_Area, out hv_Row, out hv_Column);
ShowText(hv_Class[i - 1], hv_Row + 50, hv_Column, "green");
}
if (SaveROI(roi))
{
ShowText("训练完毕", "green");
}
else
{
ShowText("训练数据保存失败", "red");
}
#endregion
HOperatorSet.ClearOcrClassMlp(hv_OcrHandle);
}
catch (HalconException HDevExpDefaultException)
{
MessageBox.Show(HDevExpDefaultException.Message);
}
ho_Rectangle.Dispose();
ho_Mono.Dispose();
ho_MonoReduced_OCR.Dispose();
ho_Symbols_OCR.Dispose();
ho_testRegion.Dispose();
}
#endregion
#region 字符识别测试
/// <summary>
/// 字符识别测试
/// </summary>
/// <param name="obj"></param>
private void OcrReadTest(object obj)
{
OcrWork(SelectVEI);
}
#endregion
#region OCR识别
/// <summary>
/// OCR识别
/// </summary>
/// <param name="RM">区域对象(用于图像校正)</param>
/// <param name="roi"></param>
public bool OcrWork(VisualEngineeringItems vei)
{
bool bl = true;
if (vei.ID <= 0)
{
ShowText("视觉工程功能项目为空", "red");
return bl;
}
//1,获取图像
if (!GetImage())
{
return bl;
}
if (!ImageCorrecting(Ho_Image, vei.ImageCorrectionRM))
{
ShowText("图像校正失败", "red");
return bl;
}
foreach (V_ROI roi in vei.MyRectangleModel.MyRoiList)
{
bl = OcrDistinguish(roi) == true ? bl : false;
}
return bl;
}
private bool OcrDistinguish(V_ROI roi)
{
bool bl = false;
HObject ho_Image, ho_TmpObj_Mono;
HObject ho_TmpObj_MonoReduced_OCR_01_0;
HObject ho_Symbols_OCR_01_0, ho_testRegion = null;
HTuple hv_Area = null;
HTuple hv_TmpCtrl_ResultHandle_OCR_01_0 = null;
HTuple hv_SymbolNames_OCR_01_0 = null, hv_Confidences_OCR_01_0 = null;
// Initialize local and output iconic variables
HOperatorSet.GenEmptyObj(out ho_Image);
HOperatorSet.GenEmptyObj(out ho_TmpObj_Mono);
HOperatorSet.GenEmptyObj(out ho_TmpObj_MonoReduced_OCR_01_0);
HOperatorSet.GenEmptyObj(out ho_Symbols_OCR_01_0);
HOperatorSet.GenEmptyObj(out ho_testRegion);
try
{
//读取OCR分类器
if (!roi.ReadOcrOcrClassMlp())
{
ShowText("读取OCR分类器失败", "red");
return false;
}
roi.Initialize();
ho_TmpObj_Mono.Dispose();
HOperatorSet.AccessChannel(CorrectingImage, out ho_TmpObj_Mono, 1);
ho_TmpObj_MonoReduced_OCR_01_0.Dispose();
HOperatorSet.ReduceDomain(ho_TmpObj_Mono, roi.ho_OutlineROI, out ho_TmpObj_MonoReduced_OCR_01_0);
HOperatorSet.FindText(ho_TmpObj_MonoReduced_OCR_01_0, roi.hv_TextModel, out hv_TmpCtrl_ResultHandle_OCR_01_0);
ho_Symbols_OCR_01_0.Dispose();
HOperatorSet.GetTextObject(out ho_Symbols_OCR_01_0, hv_TmpCtrl_ResultHandle_OCR_01_0, "all_lines");
HOperatorSet.ClearTextResult(hv_TmpCtrl_ResultHandle_OCR_01_0);
//ShowObj(ho_TmpObj_MonoReduced_OCR_01_0);
//HOperatorSet.SetDraw(HWindowWPF.HalconWindow, "fill");
SetDraw("fill");
// HOperatorSet.SetColored(HWindowWPF.HalconWindow, 3);
SetColored(3);
ShowObj(ho_Symbols_OCR_01_0);
HOperatorSet.DoOcrMultiClassMlp(ho_Symbols_OCR_01_0, ho_TmpObj_MonoReduced_OCR_01_0, roi.hv_OcrHandle, out hv_SymbolNames_OCR_01_0, out hv_Confidences_OCR_01_0);
if (hv_SymbolNames_OCR_01_0.Length > 0)
{
string str = "";
for (int i = 1; i <= hv_SymbolNames_OCR_01_0.Length; i++)
{
HOperatorSet.SelectObj(ho_Symbols_OCR_01_0, out ho_testRegion, i);
HOperatorSet.AreaCenter(ho_testRegion, out hv_Area, out hv_Row, out hv_Column);
ShowText(hv_SymbolNames_OCR_01_0[i - 1], hv_Row + 50, hv_Column, "green");
str = str + hv_SymbolNames_OCR_01_0[i - 1];
}
//判断字符是否识别成功
if (roi.Notes == str)
{
bl = true;
ShowText("正确", "green");
}
else
{
ShowText("识别失败", "red");
}
}
else
{
ShowText("未能识别到任何字符,请确认训练文件是否正确", "red");
}
}
catch (HalconException HDevExpDefaultException)
{
ho_TmpObj_Mono.Dispose();
ho_TmpObj_MonoReduced_OCR_01_0.Dispose();
ho_Symbols_OCR_01_0.Dispose();
HTuple err = new HTuple();
err[0] = "OCR识别失败";
err[1] = HDevExpDefaultException.Message;
ShowText(err, "red");
}
ho_TmpObj_Mono.Dispose();
ho_TmpObj_MonoReduced_OCR_01_0.Dispose();
ho_Symbols_OCR_01_0.Dispose();
return bl;
}
#endregion
}
}