//时间：
//作者：
//功能：自动化测试功能
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using OpenCvSharp;
using System.Windows.Forms.DataVisualization.Charting;


namespace AutoDo
{
    public partial class FormAutoDo : Form
    {
        //全局只有一个fatorySEM
        //static FactoryHardware factorySEM = FactoryHardware.Instance;
        //ISEMControl iSEM = factorySEM.ISEM;

        //图像文件夹
        public string  m_strImgPath;

        //显示处理结果
        public Bitmap m_bitmap; 

        public FormAutoDo()
        {
            InitializeComponent();
        }

        //自动对焦过程
        private void button1_Click(object sender, EventArgs e)
        {
            //第一种方法
            var files = Directory.GetFiles(m_strImgPath, "*.tif");
            float[] values = new float[files.Length];
            
            this.dataGridView1.Rows.Clear();
            Series series = chart1.Series[0];
            series.Points.Clear();

            int x = 0;

            double smax = LoGMean(files[0]);
            int wdmax = int.Parse(System.IO.Path.GetFileNameWithoutExtension(files[0]));

            foreach (var file in files)
            {
               
                int wd = int.Parse(System.IO.Path.GetFileNameWithoutExtension(file));
                double svalue = LoGMean(file);

                if (smax < svalue)
                {
                    smax = svalue;
                    wdmax = wd;
                }

                ShowData(wd, svalue);

                x++;
            }

            this.label1.Text = "焦距:" + wdmax.ToString();
        }

        //选择图像文件夹
        private void button2_Click(object sender, EventArgs e)
        {
            System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();
            dialog.Description = "选择拍图保存的文件夹";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (string.IsNullOrEmpty(dialog.SelectedPath))
                {
                    MessageBox.Show("图像文件夹不能为空");
                    return;
                }

                m_strImgPath = dialog.SelectedPath;
                tBImgPath.Text = dialog.SelectedPath;

            }
        }

        //LoG算子计算
        private double LoGMean(string a_strImgPath)
        {
            //读入Img文件
            if (!File.Exists(a_strImgPath))
            {
                return 0;
            }

            Mat src, gray_src;
            int kernel_size = 3;

            src = Cv2.ImRead(a_strImgPath);
            gray_src = new Mat();
           
            src.CvtColor(ColorConversionCodes.BGR2GRAY);  

            Mat kernel = Cv2.GetStructuringElement(MorphShapes.Cross, new OpenCvSharp.Size(10, 10));
            Cv2.MorphologyEx(src, src, MorphTypes.Close, kernel);

            Cv2.GaussianBlur(src, src, new OpenCvSharp.Size(3, 3), 0, 0);
            Cv2.Laplacian(src, src, MatType.CV_8UC3, kernel_size);
            Cv2.ConvertScaleAbs(src, src);

            //图像的平均灰度

            double meanValue = 0.0;
            meanValue = Cv2.Mean(src)[0];
            return meanValue;
        }

        //梯度计算
        private double Tenengrad(string a_strImgPath)
        {
            //读入Img文件
            if (!File.Exists(a_strImgPath))
            {
                return 0;
            }

            Mat src;
            src = Cv2.ImRead(a_strImgPath);
          
            src.CvtColor(ColorConversionCodes.BGR2GRAY);

            Mat kernel = Cv2.GetStructuringElement(MorphShapes.Cross, new OpenCvSharp.Size(10, 10));
            Cv2.MorphologyEx(src, src, MorphTypes.Close, kernel);

            Cv2.GaussianBlur(src, src, new OpenCvSharp.Size(3, 3), 0, 0);
            Cv2.Sobel(src, src, MatType.CV_8UC1, 1, 1);
            //图像的平均灰度
            double meanValue = 0.0;
            meanValue = Cv2.Mean(src)[0];
            return meanValue;
        }

        //梯度计算
        private double TTgrad(string a_strImgPath)
        {
            //读入Img文件
            if (!File.Exists(a_strImgPath))
            {
                return 0;
            }

            Mat src;
            src = Cv2.ImRead(a_strImgPath);

            src.CvtColor(ColorConversionCodes.BGR2GRAY);

            Mat kernel = Cv2.GetStructuringElement(MorphShapes.Cross, new OpenCvSharp.Size(10, 10));
            Cv2.MorphologyEx(src, src, MorphTypes.Close, kernel);

            Mat scalex = new Mat();
            Mat scaley = new Mat();

            Cv2.Scharr(src, src, src.Depth(),1, 0);
            Cv2.ConvertScaleAbs(src, scalex);

            Cv2.Scharr(src, src, src.Depth(), 0, 1);
            Cv2.ConvertScaleAbs(src, scaley);

            Cv2.AddWeighted(scalex, 0.5, scaley, 0.5, 0, src);

            //图像的平均灰度
            double meanValue = 0.0;
            meanValue = Cv2.Mean(src)[0];
            return meanValue;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            //第二种方法
            var files = Directory.GetFiles(m_strImgPath, "*.tif");
            float[] values = new float[files.Length];

            this.dataGridView1.Rows.Clear();
            Series series = chart1.Series[0];
            series.Points.Clear();


            double smax = Tenengrad(files[0]);
            int wdmax = int.Parse(System.IO.Path.GetFileNameWithoutExtension(files[0]));


            int x = 0;
            foreach (var file in files)
            {
                
                int wd = int.Parse(System.IO.Path.GetFileNameWithoutExtension(file));
                double svalue = Tenengrad(file);


                if (smax < svalue)
                {
                    smax = svalue;
                    wdmax = wd;
                }

                ShowData(wd, svalue);
                x++;
            }

            this.label1.Text = "焦距:" + wdmax.ToString();
        }

        //显示数据
        private void ShowData(int wd, double svalue)
        {
            //绘制评价函数曲线s
            Series series = chart1.Series[0];            
            series.Points.AddXY(wd, svalue);

            //显示评价函数数值
            
            int index = this.dataGridView1.Rows.Add();
            this.dataGridView1.Rows[index].Cells[0].Value = wd;
            this.dataGridView1.Rows[index].Cells[1].Value = svalue;
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void button4_Click(object sender, EventArgs e)
        {
            var files = Directory.GetFiles(m_strImgPath, "*.tif");
            float[] values = new float[files.Length];

 
            double smax1 = LoGMean(files[0]);
            int wdmax1 = int.Parse(System.IO.Path.GetFileNameWithoutExtension(files[0]));

            double smax2 = Tenengrad(files[0]);
            int wdmax2 = wdmax1;

            double smax3 = TTgrad(files[0]);
            int wdmax3 = wdmax1;



            int x = 0;
            foreach (var file in files)
            {

                int wd = int.Parse(System.IO.Path.GetFileNameWithoutExtension(file));
                double svalue1 = LoGMean(file);
                double svalue2 = Tenengrad(file);
                double svalue3 = TTgrad(file);


                if (smax1 < svalue1)
                {
                    smax1 = svalue1;
                    wdmax1= wd;
                }

                if (smax2 < svalue2)
                {
                    smax2 = svalue2;
                    wdmax2 = wd;
                }

                if (smax3 < svalue3)
                {
                    smax3 = svalue3;
                    wdmax3 = wd;
                }

                x++;
            }

            this.label2.Text = "";
            this.label2.Text = "LoG = " + wdmax1.ToString() + "，梯度 = " + wdmax2.ToString() + "，滤波 = " + wdmax3.ToString();

            
            if (wdmax1 == wdmax2 || wdmax1 == wdmax3)
            {
                
                this.label2.Text += "，焦距 = " + wdmax1.ToString();
            }
            else if (wdmax1 == wdmax2 || wdmax2 == wdmax3)
            {
                
                this.label2.Text += "，焦距 = " + wdmax2.ToString();
            }
            else if (wdmax3 == wdmax2 || wdmax1 == wdmax3)
            {
               
                this.label2.Text += "，焦距 = " + wdmax3.ToString();
            }
            else
            {
                this.label2.Text += "，对焦失败。";
            }



            
        }

        private void button5_Click(object sender, EventArgs e)
        {
            //第一种方法
            var files = Directory.GetFiles(m_strImgPath, "*.tif");
            float[] values = new float[files.Length];

            this.dataGridView1.Rows.Clear();
            Series series = chart1.Series[0];
            series.Points.Clear();

            int x = 0;

            double smax = TTgrad(files[0]);
            int wdmax = int.Parse(System.IO.Path.GetFileNameWithoutExtension(files[0]));

            foreach (var file in files)
            {

                int wd = int.Parse(System.IO.Path.GetFileNameWithoutExtension(file));
                double svalue = TTgrad(file);

                if (smax < svalue)
                {
                    smax = svalue;
                    wdmax = wd;
                }

                ShowData(wd, svalue);

                x++;
            }

            this.label1.Text = "焦距:" + wdmax.ToString();
        }
    }
}
