2016年6月2日 星期四

C#-examination-a

題目要求:
將圖切成 3*5 份去掃描,將對比最高的圖顯示出來 (找瑕疵)
圖片:L02.jpg


##ReadMore##

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using AForge.Imaging.Formats;
using AForge.Imaging.Filters;
using System.Diagnostics;
using AForge.Imaging;
using AForge.Math;

namespace examination_a
{
    public partial class Form1 : Form
    {
        Bitmap srcImg, grayImg, cropImg;

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            srcImg = ImageDecoder.DecodeFromFile("L02.jpg");
            pictureBox1.Image = srcImg;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Crop cropFilter = new Crop(new Rectangle(1, 1, 2560, 2560));
            Bitmap templateImg = cropFilter.Apply(srcImg);

            Grayscale grayFilter = new Grayscale(0.2125, 0.7154, 0.0721);
            grayImg = grayFilter.Apply(templateImg);

            pictureBox3.Image = grayImg;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            Graphics g = Graphics.FromImage(srcImg);
            Stopwatch stopWatch = new Stopwatch();
            stopWatch.Reset();
            stopWatch.Start();

            double maxStdDev = -1;
            int ii = 0, jj = 0;

            for (int i = 0; i < 5; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    Crop matchCropFilter = new Crop(new Rectangle(i * 512, j * 512, 512, 512));
                    cropImg = matchCropFilter.Apply(grayImg);

                    g.DrawRectangle(new Pen(Color.White), i * 512, j * 512, 512, 512);

                    ImageStatistics stat = new ImageStatistics(cropImg);
                    Histogram gray = stat.Gray;

                    listBox1.Items.Add("(" + i + ", " + j + ") = " + gray.StdDev.ToString());

                    if (gray.StdDev > maxStdDev)
                    {
                        maxStdDev = gray.StdDev;
                        ii = i;
                        jj = j;
                    }
                }
            }

            g.DrawRectangle(new Pen(Color.Red), ii * 512, jj * 512, 512, 512);
            textBox2.Text = maxStdDev.ToString();
            pictureBox2.Image = srcImg;

            TimeSpan ts = stopWatch.Elapsed;
            textBox1.Text = ts.ToString();
        }
    }
}

沒有留言:

張貼留言