using Community; using HalconDotNet; using Model.Vision; using System; using System.Linq; using System.Windows; namespace ViewModel.Vision { /// /// OCR_VM /// partial class HalconVisual { #region 各种方法 /// /// 创建图像校正模型 /// public DelegateCommand CreateImageCorrectionModelCommand { get; set; } /// /// 图像校正测试 /// public DelegateCommand ImageCorrectionTestCommand { get; set; } /// /// 新增OCR roi /// public DelegateCommand AddOcrRoiCommand { get; set; } /// /// 保存OCR roi /// public DelegateCommand SaveOcrRoiCommand { get; set; } /// /// 字体训练 /// public DelegateCommand FontTrainingCommand { get; set; } /// /// OCR字符读取识别测试 /// public DelegateCommand OcrReadTestCommand { get; set; } #endregion #region 校正后的图像 /// /// 校正后的图像 /// HObject CorrectingImage; #endregion #region 选中的Ocr ROI private V_ROI selectOcrRoi; /// /// 选中的Ocr ROI /// public V_ROI SelectOcrRoi { get { return selectOcrRoi; } set { selectOcrRoi = value; this.RaisePropertyChanged("SelectOcrRoi"); } } #endregion #region OCR相关初始化 /// /// OCR相关初始化 /// public void V_OcrVMInitialization() { CreateImageCorrectionModelCommand = new DelegateCommand(); CreateImageCorrectionModelCommand.ExecuteAction = new Action(CreateImageCorrectionModel); ImageCorrectionTestCommand = new DelegateCommand(); ImageCorrectionTestCommand.ExecuteAction = new Action(ImageCorrectionTest); AddOcrRoiCommand = new DelegateCommand(); AddOcrRoiCommand.ExecuteAction = new Action(AddOcrRoi); SaveOcrRoiCommand = new DelegateCommand(); SaveOcrRoiCommand.ExecuteAction = new Action(SaveOcrRoi); FontTrainingCommand = new DelegateCommand(); FontTrainingCommand.ExecuteAction = new Action(FontTraining); OcrReadTestCommand = new DelegateCommand(); OcrReadTestCommand.ExecuteAction = new Action(OcrReadTest); } #endregion #region 保存字符识别ROI /// /// 保存字符识别ROI /// /// 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 /// /// 新增字符识别ROI /// /// 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 创建图像校正模型 /// /// 创建图像校正模型 /// /// 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 图像校正测试 /// /// 图像校正测试 /// /// private void ImageCorrectionTest(object obj) { if (SelectVEI.ImageCorrectionRM.ID > 0) { //1,获取图像 if (!GetImage()) { return; } ImageCorrecting(Ho_Image, SelectVEI.ImageCorrectionRM); ShowObj(CorrectingImage); } } #endregion #region 图像校正 /// /// 图像校正 /// public bool ImageCorrecting(HObject Image, V_RectangleModel RM, int type = 0) { bool pipeiOK = false; 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 { for (int i = 0; i <= hv_Score.TupleLength() - 1; i++) { HOperatorSet.HomMat2dIdentity(out hv_RectificationHomMat2D); var ty = RM.MyROI.ModelFeaturePiont.hv_RefRow - (hv_Row.TupleSelect(i)); var tx = RM.MyROI.ModelFeaturePiont.hv_RefColumn - (hv_Column.TupleSelect(i)); HOperatorSet.HomMat2dTranslate(hv_RectificationHomMat2D, ty, tx, out hv_RectificationHomMat2D); var ta = (hv_Angle.TupleSelect(i)); HOperatorSet.HomMat2dRotate(hv_RectificationHomMat2D, -ta, 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; if (type != 0) { HOperatorSet.HomMat2dIdentity(out hv_RectificationHomMat2D); HOperatorSet.HomMat2dTranslate(hv_RectificationHomMat2D, -ty, -tx, out hv_RectificationHomMat2D); HOperatorSet.HomMat2dRotate(hv_RectificationHomMat2D, ta, RM.MyROI.ModelFeaturePiont.hv_RefRow, RM.MyROI.ModelFeaturePiont.hv_RefColumn, out hv_RectificationHomMat2D); RM.HomMat2D = hv_RectificationHomMat2D; HOperatorSet.HomMat2dToAffinePar(RM.HomMat2D, out HTuple sx, out HTuple sy, out HTuple phiH, out HTuple thetaH, out HTuple tX, out HTuple tY); var phi = phiH.TupleDeg(); ShowText("校准" + " X:" + tX.D.ToString("F3") + ", Y:" + tY.D.ToString("F3") + ", U:" + phi.D.ToString("F3"), "green", 20, 10); } else { RM.HomMat2D = hv_RectificationHomMat2D; HOperatorSet.HomMat2dToAffinePar(RM.HomMat2D, out HTuple sx, out HTuple sy, out HTuple phiH, out HTuple thetaH, out HTuple tX, out HTuple tY); var phi = phiH.TupleDeg(); ShowText("校准" + " X:" + tX.D.ToString("F3") + ", Y:" + tY.D.ToString("F3") + ", U:" + phi.D.ToString("F3"), "green", 20, 10); } //ShowObj(ho_RectifiedImage, "green"); } pipeiOK = true; } } catch (Exception) { ShowTextPer("图像校正失败", "red"); } return pipeiOK; } #endregion #region 字体训练测试 /// /// 字体训练测试 /// /// private void FontTraining(object obj) { OCRFontTraining(SelectVEI.ImageCorrectionRM, SelectOcrRoi); } #endregion #region OCR字体训练 /// /// OCR字体训练 /// /// 区域对象(用于图像校正) /// 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; } ShowObj(CorrectingImage); 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.ReadOcrClassMlp(AutoOcrFile, out hv_OcrHandle); //获取分类模型 ClearWindowAndData(); ShowObj(CorrectingImage); DrawROI(RM); 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); HOperatorSet.SetDraw(HWindowWPF.HalconWindow, "fill"); HOperatorSet.SetColored(HWindowWPF.HalconWindow, 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 字符识别测试 /// /// 字符识别测试 /// /// private void OcrReadTest(object obj) { OcrWork(SelectVEI); } #endregion #region OCR识别 /// /// OCR识别 /// /// 区域对象(用于图像校正) /// 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; } else { ShowObj(CorrectingImage); } 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"); HOperatorSet.SetColored(HWindowWPF.HalconWindow, 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 } }