using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HalconDotNet;
using System.IO;
using CvBase;
using CWindowTool;
using Newtonsoft.Json;

namespace CvImageTool.FindShapeModelByXld
{
    public class FindShapeModelByXldTool
    {
        public FileINI INI = new FileINI();
        public FindShapeModelByXldParam findShapeModelByXldParam;    //匹配参数
        private string cProcessSettingFilePath;     //当前流程配置文件的路径
        private string cImageOptSettingFilePath;    //当前算法参数文件路径
        private string cCutImageFilePath;            //当前模板截图文件路径
        private string cModelHandleFilePath;        //当前模板匹配句柄文件路径
        public string imageSelect = "";            //图像输入参数选择项
        public string affinMatrixSelect = "";      //仿射矩阵输入参数选择项
        private int cProcessIndex = -1;             //当前归属流程的索引
        private int cImageOptIndex = -1;            //当前归属算法的索引
        public bool isShowModelContour = false;
        public bool isShowROI = false;
        public bool isShowModelResult = false;
        public HObject Image;
        public HTuple AffinMatrix;
        public HObject ModelCoutour;
        public HTuple ModelHandle;
        private List<BaseProcess> process;
        private CWindows[] cCWindows;


        public FindShapeModelByXldTool(int cProcessIndex, int cImageOptIndex,
           string cProcessSettingFilePath, string cImageOptSettingFilePath, string cCutImageFilePath, string cModelHandleFilePath,
           List<BaseProcess> processes, CWindows[] cWindows)
        {
            this.cProcessSettingFilePath = cProcessSettingFilePath;
            this.cImageOptSettingFilePath = cImageOptSettingFilePath;
            this.cProcessIndex = cProcessIndex;
            this.cImageOptIndex = cImageOptIndex;
            this.cCutImageFilePath = cCutImageFilePath;
            this.cModelHandleFilePath = cModelHandleFilePath;
            this.process = processes;
            this.cCWindows = cWindows;
            findShapeModelByXldParam = new FindShapeModelByXldParam();
            Image = new HObject();
        }


        /// <summary>
        /// 读取配置文件
        /// </summary>
        /// <param name="cProcessSettingFilePath"></param>
        /// <param name="cImgeOptSettingFilePath"></param>
        /// <returns></returns>
        public bool ReadFile(string cProcessDescription)
        {
            imageSelect = ""; affinMatrixSelect = "";
            if (!File.Exists(cProcessSettingFilePath) || !File.Exists(cImageOptSettingFilePath)) return false;
            imageSelect = FileINI.ReadValueFromIniFile(cProcessDescription, "Image", "", cProcessSettingFilePath);
            affinMatrixSelect = FileINI.ReadValueFromIniFile(cProcessDescription, "Matrix", "", cProcessSettingFilePath);
            isShowModelContour = Convert.ToBoolean(FileINI.ReadValueFromIniFile(cProcessDescription, "ShowModelContour", "", cProcessSettingFilePath));
            isShowModelResult = Convert.ToBoolean(FileINI.ReadValueFromIniFile(cProcessDescription, "ShowModelResult", "", cProcessSettingFilePath));
            isShowROI = Convert.ToBoolean(FileINI.ReadValueFromIniFile(cProcessDescription, "ShowROI", "", cProcessSettingFilePath));
            findShapeModelByXldParam = JsonConvert.DeserializeObject<FindShapeModelByXldParam>(File.ReadAllText(cImageOptSettingFilePath));
            return true;
        }

        /// <summary>
        /// 保存模板匹配句柄
        /// </summary>
        public void SaveModelHandle()
        {
            if (File.Exists(cModelHandleFilePath)) File.Delete(cModelHandleFilePath);
            HOperatorSet.WriteShapeModel(ModelHandle, cModelHandleFilePath);
        }

        /// <summary>
        /// 保存模板图像
        /// </summary>
        public void SaveModelCoutour()
        {
            //if (File.Exists(cCutImageFilePath)) File.Delete(cCutImageFilePath);
            //HOperatorSet.WriteRegion(ModelCoutour, cCutImageFilePath);
        }

        /// <summary>
        /// 读模板句柄
        /// </summary>
        public bool ReadModelHandle()
        {
            if (!File.Exists(cModelHandleFilePath)) return false;
            if (ModelHandle != null) HOperatorSet.ClearShapeModel(ModelHandle);
            HOperatorSet.ReadShapeModel(cModelHandleFilePath, out ModelHandle);
            return true;
        }

        /// <summary>
        /// 读模板图像
        /// </summary>
        public bool ReadModelCoutour()
        {
            //if (!File.Exists(cCutImageFilePath)) return false;
            //if (ModelCoutour != null) ModelCoutour.Dispose();
            //HOperatorSet.ReadRegion(out ModelCoutour, cCutImageFilePath);
            return true;
        }


        /// <summary>
        /// 写配置文件
        /// </summary>
        /// <param name="cProcessSettingFilePath"></param>
        /// <param name="cImgeOptSettingFilePath"></param>
        /// <returns></returns>
        public bool WriteFile(string cProcessDescription)
        {
            FileINI.WriteValueFromIniFile(cProcessDescription, "Image", imageSelect, cProcessSettingFilePath);
            FileINI.WriteValueFromIniFile(cProcessDescription, "Matrix", affinMatrixSelect, cProcessSettingFilePath);
            FileINI.WriteValueFromIniFile(cProcessDescription, "ShowModelContour", isShowModelContour.ToString(), cProcessSettingFilePath);
            FileINI.WriteValueFromIniFile(cProcessDescription, "ShowModelResult", isShowModelResult.ToString(), cProcessSettingFilePath);
            FileINI.WriteValueFromIniFile(cProcessDescription, "ShowROI", isShowROI.ToString(), cProcessSettingFilePath);
            var json = JsonConvert.SerializeObject(findShapeModelByXldParam, Formatting.Indented);
            File.WriteAllText(cImageOptSettingFilePath, json);
            return true;
        }

        /// <summary>
        /// 创建模板
        /// </summary>
        public void CreateShapModel()
        {
            if (ModelHandle != null) HOperatorSet.ClearShapeModel(ModelHandle);
            if (findShapeModelByXldParam.ScaleEnable)
            {
                HOperatorSet.CreateScaledShapeModelXld(ModelCoutour, "auto", AngleConvert.Degress2Rads(findShapeModelByXldParam.AngleStart),
                     AngleConvert.Degress2Rads(findShapeModelByXldParam.AngleExtent),"auto", findShapeModelByXldParam.MinScale, findShapeModelByXldParam.MaxScale,
                    "auto", "auto", "ignore_local_polarity", findShapeModelByXldParam.MinContrast, out ModelHandle);
            }
            else
            {
                HOperatorSet.CreateShapeModelXld(ModelCoutour, "auto", AngleConvert.Degress2Rads(findShapeModelByXldParam.AngleStart), AngleConvert.Degress2Rads(findShapeModelByXldParam.AngleExtent),
                   "auto", "auto", "ignore_local_polarity", findShapeModelByXldParam.MinContrast, out ModelHandle);
            }
            SaveModelCoutour();
        }


        public void Running(out HObject resultContours, out HTuple row, out HTuple col, out HTuple angle, out HTuple score)
        {
            row = new HTuple(); col = new HTuple(); angle = new HTuple(); score = new HTuple(); resultContours = new HObject();
            if (Image == null) return;
            ReadModelHandle();
            HOperatorSet.SetSystem("clip_region", "false");
            HOperatorSet.GenRectangle1(out HObject rectange, findShapeModelByXldParam.ROIStartRow,
                findShapeModelByXldParam.ROIStartColumn, findShapeModelByXldParam.ROIEndRow, findShapeModelByXldParam.ROIEndColumn);
            string[] imageOptAndParamName = affinMatrixSelect.Split('_');
            ProcessTool.Instance.FindImageOpt(process[cProcessIndex], imageOptAndParamName[0], out BaseImageOpt byImageOpt, out int byIndex);
            if (byIndex >= 0)
                process[cProcessIndex].BaseImageOutParams[byIndex].GetHTupleValue(imageOptAndParamName[1], out AffinMatrix);
            else
                AffinMatrix = null;
            if (findShapeModelByXldParam.Affin && AffinMatrix != null && AffinMatrix.Length == 6)
            {
                HOperatorSet.AffineTransRegion(rectange, out HObject NROI, AffinMatrix, "nearest_neighbor");
                rectange.Dispose();
                rectange = NROI;
            }
            HOperatorSet.ReduceDomain(Image, rectange, out HObject reduceImage);
            rectange.Dispose();
            HTuple scale = null;
            if (findShapeModelByXldParam.ScaleEnable)
            {
                HOperatorSet.FindScaledShapeModel(reduceImage, ModelHandle, AngleConvert.Degress2Rads(findShapeModelByXldParam.AngleStart), AngleConvert.Degress2Rads(findShapeModelByXldParam.AngleExtent),
                              findShapeModelByXldParam.MinScale, findShapeModelByXldParam.MaxScale, findShapeModelByXldParam.MinScore, findShapeModelByXldParam.NumMatches, 0.5,
                                "least_squares", 0, 0.9, out row, out col, out angle, out scale, out score);
            }
            else
            {
                HOperatorSet.FindShapeModel(reduceImage, ModelHandle, AngleConvert.Degress2Rads(findShapeModelByXldParam.AngleStart), AngleConvert.Degress2Rads(findShapeModelByXldParam.AngleExtent),
                       findShapeModelByXldParam.MinScore, findShapeModelByXldParam.NumMatches, 0.5, "least_squares", 0, 0.9,
                       out row, out col, out angle, out score);
            }
            reduceImage.Dispose();
            if (score.Length > 0)
            {
                HOperatorSet.GetShapeModelContours(out HObject modelContours, ModelHandle, 1);
                HOperatorSet.VectorAngleToRigid(0, 0, 0, row[0], col[0], angle[0], out HTuple homMat2D);
                if (findShapeModelByXldParam.ScaleEnable)
                    HOperatorSet.HomMat2dScale(homMat2D, scale, scale, row[0], col[0], out homMat2D);
                HOperatorSet.AffineTransContourXld(modelContours, out resultContours, homMat2D);
                modelContours.Dispose();
                angle = AngleConvert.Rads2Degress(angle);
            }
            else
            {
                row = new HTuple();
                col = new HTuple();
                angle = new HTuple();
                resultContours = new HObject();
            }
        }
    }
}
 

Logo

聚焦RDK与具身智能,汇集机器人开发教程、开源案例和技术交流

更多推荐