﻿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 Emgu.CV;
using Emgu.CV.Structure;

namespace EmguCV_ViewImage
{
    public partial class Form1 : Form
    {
        Image<Bgr, byte> _InputImage;
        Image<Gray, byte> _GrayImage;

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //string fileName = "C:\\Emgu\\blackandwhite.jpg";
            string fileName;
            OpenFileDialog ofd = new OpenFileDialog();
            
            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                fileName = ofd.FileName;
                _InputImage = new Image<Bgr, byte>(fileName);

                if (_InputImage == null)
                {
                    MessageBox.Show("Error reading image");
                    return;
                }

                panAndZoomPictureBox2.Image = _InputImage.ToBitmap();
                //panAndZoomPictureBox2.FunctionalMode = Emgu.CV.UI.ImageBox.FunctionalModeOption.Everything;

                _GrayImage = _InputImage.Convert<Gray, byte>();
                panAndZoomPictureBox1.Image = _GrayImage.Bitmap;

                DenseHistogram hist = new DenseHistogram(256, new RangeF(0, 255));
                hist.Calculate(new Image<Gray, byte>[] { _InputImage[0] }, false, null);

                Mat m = new Mat();
                hist.CopyTo(m);

                histogramBox1.AddHistogram("Blue", Color.Blue, m, 256, new float[] { 0, 256 });
                histogramBox1.Refresh();

                Image<Gray, byte> _imgCanny = new Image<Gray, byte>(_InputImage.Width, _InputImage.Height, new Gray(0));
                _imgCanny = _InputImage.Canny(100, 100);
                panAndZoomPictureBox1.Image = _imgCanny.ToBitmap();


                double[] minValue;
                double[] maxValue;
                double avgValue;
                Point[] minLocation;
                Point[] maxLocation;

                //hist.MinMax(out minValue, out maxValue, out minLocation, out maxLocation);
                _imgCanny.MinMax(out minValue, out maxValue, out minLocation, out maxLocation);

                //avgValue = _GrayImage.GetAverage().Intensity;
                avgValue = _imgCanny.GetAverage().Intensity;
                
                txtBoxMax.Text = maxValue[0].ToString();
                txtBoxMin.Text = minValue[0].ToString();
                txtBoxAvg.Text = avgValue.ToString();
                
            }


        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}
