2016年6月6日 星期一

JavaBean 模組化類別 (打包重複功能)

說明,寫兩個檔案:
  1. helloBean.java → 接收一個字串 name,並回傳 “Hello, “ + name
  2. helloBean.jsp → 載入 JavaBean,印出結果。
##ReadMore##
---
前言:
在網頁語言 JSP 及 Servlet 之開發過程中,常常會使用到相同功能的程式,而最快的處理方法就是複製並貼上至其他的頁面,但當程式專案規模變大後,這種方式會導致後續維護及管理的困難,也使不同版本之功能難以維持一致性。
因此可以選擇使用 JavaBean 模組化技術,其主要用來設計特定功能且能夠被使用、復用、替代和連接的副程式,事實上它也只是一般的 Java 類別,但必須遵循 JavaBean API 之規範,例如特定的命名、建構元、方法之規定。

Reference:
國立中山大學程式諮詢網 - 簡介 JavaBean

---
/opt/apache-tomcat-8.0.30/webapps/Test/WEB-INF/src/helloBean.java
package bean;

public class helloBean{
    public String helloBean(String name){
        String message = "Hello, " + name + "!!";
        return message;
    }
}

‧ 編譯檔案為 .class,且檔案位置為:
/opt/apache-tomcat-8.0.30/webapps/Test/WEB-INF/classes/bean/helloBean.class

---
/opt/apache-tomcat-8.0.30/webapps/Test/helloBean.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" %>

<!-- 載入 JavaBean 的語法 -->
<jsp:useBean id='objHello' scope='application' class='bean.helloBean' />

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>demo JavaBeans</title>
</head>
<body>
<%
    String message;
    message = objHello.helloBean("tete");
    out.println(message);
%>
</body>
</html>

---
測試:
http://localhost:8080/Test/helloBean.jsp

寫一個 HTML 傳送表單資料至 JSP

說明:
寫兩個檔案:

  1. request.html → 做一個表單,可傳送資料出去。
  2. request.jsp → 讀取 get 請求,並輸出傳來的資料內容。

---
前言:
HTTP Request 請求,常用的有 GET 及 POST 方法,於網路查詢即可得知兩者差異,這邊就不加說明,直接 codeing 實作。

##ReadMore##
---
兩檔案路徑同樣放至:/opt/apache-tomcat-8.0.30/webapps/Test/

---
request.html
<html>
  <head>>
 
  </head>
   
  <body>
    <form action="request.jsp" method="get">
               請輸入資訊:<input type="text" name="info">
      <input type="submit" value="傳送">
    </form> 
  </body>
</html>

---
request.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>

</head>

<body>
<% 
request.setCharacterEncoding("UTF-8");
//String content=new String(request.getParameter("info").getBytes("UTF-8"));
String content = request.getParameter("info");

if(content == null){
    content = "null";
}else{
    content = new String(request.getParameter("info").getBytes("UTF-8"));       
}
//String content=request.getParameter("info");
%>                                                          
<h2>顯示…</h2>                                              
<h2>收到的訊息:<%=content %></h2>                          
</body>                                                     
</html>

---
測試網址:
http://localhost:8080/Test/request.html

送出表單後,會直接跳轉至
http://localhost:8080/Test/request.jsp

---
也可以硬改網址,直接加入參數及資料給 JSP,例如:
http://localhost:8080/Test/request.jsp?info=hehe

因此也可以發現,從安全性來看,POST (資料參數不會附在網址上)遠優於 GET 求請方式。

Roseapple Pi - 於 Android 之 USB to TTL 連線 + ADB 指令控制

說明:
  1. 使用 USB to TTL 工具,並以 minicom 指令連線至蓮霧派(android)。
  2. 以 ADB 指令控制蓮霧派(android)。
##ReadMore##
---
Step 1. USB to TTL 工具接線:

---
Step 2. 於 Debian 下安裝 minicom 及 ADB 指令:
~$ sudo apt-get install minicom
~$ sudo apt-get install android-tools-adb android-tools-fastboot

---
Step 3. 設定 minicom:
~$ minicom -s

序列埠設定:

按「離開本畫面」可以進入 minicom 連線至蓮霧派 Android 系統文字畫面。
---
Step 4. 設定蓮霧派 ADB TCP port 為 5555:
於 minicom 畫面,控制蓮霧派 Android ADB 指令 -
netcfg → 查看 ip,假設為 192.168.1.100
setprop service.adb.tcp.port 5555 && stop adbd && start adbd

---
Step 5. 網路連線至蓮霧派:
於 Debian 終端機下 ADB 網路連線指令:

adb connect 192.168.1.100

確認裝置有連到,於終端機:
adb devices
---
Step 6. 可以斷開 USB to TTL 連接線路,直接使用終端機透過網路下指令:
adb shell /system/bin/screencap -p /sdcard/screenshot.png → 截圖
adb shell → adb install *.apk → 安裝 apk 檔

查看溫度:
adb -s 192.168.31.124:5555 shell
cat /sys/class/thermal/thermal_zone*/temp

關機:
adb shell reboot -p
adb shell shutdown
adb shell halt

---
其他備註. 使用 `adb connect RoseapplePi.IP` 連接後,可以開啟 Android Studio 軟體找到該裝置,直接燒錄 app 程式。




2016年6月4日 星期六

Apache Tomcat 環境建置

‧ 前言:
Apache Tomcat 是 Apache 軟體基金會下之 Jakarta 項目專案所開發出來的免費開源軟體,內含有 HTTP 伺服器,因此也可以被視作為一個單獨的網頁伺服器;另外主要特色為支援 Java Servlet 及 JavaServer Page (JSP),並且透過 XML 格式之設定檔來管理及控制網頁路徑。

##ReadMore##
---
Step 0. 安裝 Java JDK
可以參考本站文章「設定指令優先權(Java 安裝為例)」,本例使用版本:
~$ java -version

java version "1.8.0_45"
Java(TM) SE Runtime Environment (build 1.8.0_45-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.45-b02, mixed mode)

---
Step 1. 下載檔案
官方下載 Apache Tomcat,
本文使用版本為 apache-tomcat-8.0.30-src.tar.gz

---
Step 2. 解壓縮
於 Linux 系統環境下,通常習慣將第三方協力軟體放置到 “/opt“ 目錄下(需 ROOT)。
~$ sudo tar xfva apache-tomcat-8.0.30-src.tar.gz -C /opt

---
Step 3. 啟動 apache-tomcat 服務
至解壓縮目錄內之 “bin“ 目錄下執行運作服務 Shell Scrip 檔。
~$sudo sh /opt/apache-tomcat-8.0.30/bin/startup.sh

---
Step 4. 測試網頁
開啟瀏覽器鍵入網址 “http://localhost:8080/“,若有正確啟動服務會看到下圖畫面:

---
Step 5. 建立專案
使用 Apache Tomcat 必須遵守其檔案目錄配置的規範,
以路徑 /opt/apache-tomcat-8.0.30/webapps 做為網頁之根目錄 (Root) 開始建立專案目錄。


---
Step 6. 寫 JSP 測試:/opt/apache-tomcat-8.0.30/webapps/Test/hello.jsp
<%@ page contentType="text/html;charset=UTF-8" %>                               
<html>
<head>
    <title>Hello</title><br>
</head>
<body>
    <h3>Input Name</h3>
    <form action="/TestApp/Hello" method="get">
        請輸入姓名:
        <input type="text" name="UserID" />
        <input type="submit" value="Send" />
    </form>
</body>
</html>

---
Step 7-1. 寫 Servlet 測試:/opt/apache-tomcat-8.0.30/webapps/Test/WEB-INF/src/HelloServlet.java
import java.io.*;                                                            
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
                    throws ServletException, IOException {
        // 下面兩行讓中文字能正確顯示
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");

        PrintWriter out = response.getWriter();
        out.println("<HTML>");
        out.println("<BODY>");
        out.println("<p>Hello! 這是我的第一支 Java servlet 程式。</p>");
        out.println("</BODY>");
        out.println("</HTML>");
  }
}

Step 7-2. 以指令編譯成 .class 檔:/opt/apache-tomcat-8.0.30/webapps/Test/WEB-INF/classes/HelloServlet.class
cd /opt/apache-tomcat-8.0.30/webapps/Test/WEB-INF/src
javac *.java -d ../classes/

Step 7-3. 設定 web.xml:/opt/apache-tomcat-8.0.30/webapps/Test/WEB-INF/web.xml
<servlet>
   <servlet-name>HelloServlet</servlet-name>
   <servlet-class>HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>HelloServlet</servlet-name>
   <url-pattern>/HelloServlet</url-pattern>
</servlet-mapping>

---
Step 8-1. 測試 jsp 網址:
http://localhost:8080/Test/hello.jsp

Step 8-2. 測試 servlet 網址:
http://localhost:8080/Test/hello

2016年6月2日 星期四

C#-examination-e

題目要求:
魔術方塊,六種顏色以文字表之。
圖片共十二張:點我下載

##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.Filters;
using AForge.Imaging.Formats;
using AForge.Imaging;
using System.Drawing.Imaging;
using System.Diagnostics;
using AForge.Math;

namespace examination_e
{
    public partial class Form1 : Form
    {
        Bitmap srcImg, cropImg, confirmImg;
        String knowColor;

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            openFileDialog1.Filter = "All File(*.*)|*.*";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                srcImg = ImageDecoder.DecodeFromFile(openFileDialog1.FileName);
                pictureBox1.Image = srcImg;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            listBox1.Items.Clear();
            //因為每張魔術方塊圖大小、位置不定,慢慢抓最大最小值縮減掃描範圍
            int catchX = 250;
            int catchY = 130;
            int catchWidth = 650;
            int catchHeight = 500;

            //第一階段截取圖片,因為每張魔術方塊圖大小、位置不定先截個自訂值(畫 rectangle 慢慢測試得來的)
            Crop cropFilter = new Crop(new Rectangle(catchX, catchY, catchWidth, catchHeight));
            Bitmap scanImg = cropFilter.Apply(srcImg);
            pictureBox3.Image = scanImg;

            Graphics g = Graphics.FromImage(srcImg);
            g.DrawRectangle(new Pen(Color.Red), catchX - 1, catchY - 1, catchWidth + 2, catchHeight + 2);
            pictureBox2.Image = srcImg;

            //Color 陣列用來儲存第一階段截取範圍內全部 colorPixel,容器 +10 避免誤差,造成超出陣列
            Color[,] colorPixel = new Color[catchX + catchWidth + 10, catchY + catchHeight + 10];

            //初始化,魔術方塊區域之座標最大、最小值
            int max_x = 0, max_y = 0, min_x = catchX + catchWidth, min_y = catchY + catchHeight;

            //開始取得第一階段截取範圍全部的 colorPixel
            for (int i = catchX; i < catchX + catchWidth; i++)
            {
                for (int j = catchY; j < catchY + catchHeight; j++)
                {
                    colorPixel[i, j] = srcImg.GetPixel(i, j);
                }
            }

            //掃描第一階段截取之範圍, 取得非黑色的座標之最大、最小座標 max_x, max_y, min_x, min_y
            for (int i = catchX; i < catchX + catchWidth; i++)
            {
                for (int j = catchY; j < catchY + catchHeight; j++)
                {
                    // 設 RGB < 90 為黑色,非魔術方塊區域。
                    if (colorPixel[i, j].R < 90 && colorPixel[i, j].G < 90 && colorPixel[i, j].B < 90) { /*nothing to do*/ }
                    // 第一層過濾,非黑色,則有可能是彩色圖,但有誤差,所以還要第二層過濾。
                    else
                    {
                        // 設 RGB < 90 為黑色,非魔術方塊區域。
                        if (colorPixel[i - 2, j - 2].R < 90 && colorPixel[i - 2, j - 2].G < 90 && colorPixel[i - 2, j - 2].B < 90) { /* nothing to do */ }
                        //第二層過濾,判斷座標 [i-2, j-2] colorPixel 必需不是黑色 (即捕捉連續彩色→但只能捉到魔術方塊左上角座標,右下座標仍有誤差)
                        else
                        {
                            // 設 RGB < 90 為黑色,非魔術方塊區域。
                            if (colorPixel[i + 2, j + 2].R < 90 && colorPixel[i + 2, j + 2].G < 90 && colorPixel[i + 2, j + 2].B < 90) { /* nothing to do */ }
                            //第三層過濾,判斷座標 [i+2, j+2] colorPixel 必需不是黑色 (即捕捉連續彩色→測試後可以正確抓到魔術方塊完整範圍)
                            else
                            {
                                // 抓魔術方塊區域之座標最大、最小值
                                if (max_x < i)
                                    max_x = i;
                                if (max_y < j)
                                    max_y = j;
                                if (min_x > i)
                                    min_x = i;
                                if (min_y > j)
                                    min_y = j;
                            }

                        }
                    }
                }
            }

            //得到魔術方塊區域之最大、最小座標 max_x, max_y, min_x, min_y,算差值得到魔術方塊之 Height= calcH, Width=calcW
            int calcW = max_x - min_x;
            int calcH = max_y - min_y;

            //做記號至 srcImg 測試確認用
            g.DrawRectangle(new Pen(Color.Red), min_x, min_y, calcW, calcH);
            textBox1.Text = "BottomRight=(" + max_x + ", " + max_y + ")";
            textBox2.Text = "TopLeft=(" + min_x + ", " + min_y + ")";
            textBox3.Text = "width=" + calcW + ", height=" + calcH;

            //第二階段截取圖片,得到完整魔術方塊的區域 = cropImg
            Crop cropFilter2 = new Crop(new Rectangle(min_x, min_y, calcW, calcH));
            cropImg = cropFilter2.Apply(srcImg);

            //魔術方塊的區域印至 pictureBox3 再確認
            pictureBox3.Image = cropImg;

            /*
            //手動測試用
            int jjj = 0;
            int iii = 2;
            Crop cropFilterTest = new Crop(new Rectangle(iii * calcW / 3, jjj * calcH / 3, calcW / 3, calcH / 3));
            confirmImg = cropFilterTest.Apply(cropImg);
            pictureBox4.Image = confirmImg;
             */

            //掃描魔術方塊區域
            for (int jj = 0; jj < 3; jj++)
            {
                for (int ii = 0; ii < 3; ii++)
                {
                    //第三階段截取,割成 3×3, 每一格單位: Width=calcH/3, Height=calcH/3,以 for-loop 掃描 
                    Crop cropFilter3 = new Crop(new Rectangle(ii * calcW / 3, jj * calcH / 3, calcW / 3, calcH / 3));
                    confirmImg = cropFilter3.Apply(cropImg);

                    //傳送單塊顏色中心點之 RGB 判別顏色
                    Color confirmPixel = confirmImg.GetPixel(confirmImg.Width / 2, confirmImg.Height / 2);
                    //寫一個 function confirmColor 內有色表做顏色確認
                    confirmColor(confirmPixel.R, confirmPixel.G, confirmPixel.B);
                    listBox1.Items.Add("(" + jj + ", " + ii + ") = " + knowColor);
                    //listBox1.Items.Add("R,G,B = " +confirmPixel.R + "," + confirmPixel.G + "," + confirmPixel.B);
                    listBox1.Items.Add("");
                }
                listBox1.Items.Add("-----------------");
            }
            pictureBox2.Image = srcImg;     
        }

        public void confirmColor(int R, int G, int B)
        {
            //Blue
            if (R < 40 && G < 50 && B > 70 && B < 150)
                knowColor = "Blue";
            //Yellow
            else if (R > 200 && G > 170 && B > 50 && B < 96)
                knowColor = "Yellow";
            //Green
            else if (R < 80 && G > 50 && G < 160 && B > 40 && B < 100)
                knowColor = "Green";
            //Orange
            else if (R > 175 && G > 55 && G < 115 && B < 68)
                knowColor = "Orange";
            //Red
            else if (R > 100 && R < 200 && G < 55 && B < 50)
                knowColor = "Red";
            //White
            else if (R > 170 && G > 179 && B > 170)
                knowColor = "White";
            else
            {
                knowColor = "unknow";
            }
        }
    }
}

C#-examination-d

題目要求:
使用textbox show出各個blob的中心點座標
圖片:1-1.bmp

##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;
using AForge.Imaging.Formats;
using AForge.Imaging.Filters;
using AForge.Math;
using AForge.Video;

namespace examination_d
{
    public partial class Form1 : Form
    {
        Bitmap srcImg;

        public Form1()
        {
            InitializeComponent();
        }

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

        private void button2_Click(object sender, EventArgs e)
        {
            int largestarea, ii, blobcount, totalarea, avearea;
            Grayscale grayFilter = new Grayscale(0.2125, 0.7154, 0.0721);
            Bitmap grayImg = grayFilter.Apply(srcImg);
            pictureBox2.Image = grayImg;

            Threshold thresFilter = new Threshold(254);
            Bitmap bimage = thresFilter.Apply(grayImg);
            pictureBox3.Image = bimage;

            // create an instance of blob counter algorithm
            BlobCounterBase bc = new BlobCounter();
            // set filtering options
            bc.FilterBlobs = true;
            bc.MinWidth = 5;
            bc.MinHeight = 5;
            // set ordering options
            bc.ObjectsOrder = ObjectsOrder.Size;
            // process binary image
            bc.ProcessImage(bimage);
            Blob[] blobs = bc.GetObjectsInformation();
            // extract the biggest blob

            largestarea = blobs[0].Area;
            textBox1.Text = largestarea.ToString();
            blobcount = bc.ObjectsCount;
            textBox2.Text = bc.ObjectsCount.ToString();
            textBox7.Text = blobs[0].CenterOfGravity.ToString();

            totalarea = 0;
            for (ii = 0; ii < blobcount; ii++)
            {
                totalarea = totalarea + blobs[ii].Area;

                listBox1.Items.Add(blobs[ii].Area.ToString());

            }

            for (ii = 0; ii < blobcount; ii++)
            {
                listBox2.Items.Add("blobs[" + ii + "] = (" + Convert.ToInt16(blobs[ii].CenterOfGravity.X).ToString() + ", " + Convert.ToInt16(blobs[ii].CenterOfGravity.Y).ToString() + ")");
            }

            textBox4.Text = totalarea.ToString();

            avearea = totalarea / blobcount;
            textBox5.Text = avearea.ToString();

            Invert filterinv = new Invert();
            Bitmap invimg = filterinv.Apply(bimage);
            pictureBox4.Image = invimg;

            // create filter
            Subtract filtersub = new Subtract(invimg);
            // apply the filter
            Bitmap blobimg = filtersub.Apply(grayImg);
            pictureBox5.Image = blobimg;


            // gather statistics
            ImageStatistics stat = new ImageStatistics(blobimg);
            // get red channel's histogram
            Histogram gray = stat.Gray;
            int blobimgarea = stat.PixelsCountWithoutBlack;
            double blobmean = gray.Mean * blobimg.Height * blobimg.Width / blobimgarea;
            textBox6.Text = blobmean.ToString();

        }

    }
}

C#-examination-c

題目要求:
算板手(p5)的面積與中間寬度
圖片:p5.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;
using AForge.Imaging.Filters;
using AForge.Imaging.Formats;
using AForge.Math;

namespace examination_c
{
    public partial class Form1 : Form
    {
        Bitmap srcImg, tempImg;
        int x = 400, y1 = 100, y2 = 500;

        public Form1()
        {
            InitializeComponent();
        }

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

        private void button2_Click(object sender, EventArgs e)
        {
            Grayscale grayFilter = new Grayscale(0.2125, 0.7154, 0.0721);
            tempImg = grayFilter.Apply(tempImg);

            OtsuThreshold otsuFilter = new OtsuThreshold();
            tempImg = otsuFilter.Apply(tempImg);

            Invert invFilter = new Invert();
            tempImg = invFilter.Apply(tempImg);

            FillHoles holeFilter = new FillHoles();
            holeFilter.MaxHoleHeight = 100;
            holeFilter.MaxHoleWidth = 100;
            holeFilter.CoupledSizeFiltering = false;
            tempImg = holeFilter.Apply(tempImg);

            pictureBox2.Image = tempImg;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            Graphics g = Graphics.FromImage(srcImg);
            g.DrawLine(new Pen(Color.Red), new Point(x, y1), new Point(x, y2));
            pictureBox1.Image = srcImg;
        }

        private void button4_Click(object sender, EventArgs e)
        {
            Bitmap imgtwo = new Bitmap(tempImg);
            Graphics g2 = Graphics.FromImage(imgtwo);

            int[,] point = new int[x + 5, y2 + 5];
            int count = 0;
            int[] value = new int[2];

            for (int y = y1; y < y2; y++)
            {
                Color pixelColor = imgtwo.GetPixel(x, y);
                point[x, y] = pixelColor.R;
            }

            for (int y = y1; y < y2; y++)
            {
                if (point[x, y] < 20)
                {
                    if (point[x, y] != point[x, y - 1] || point[x, y] != point[x, y + 1])
                    {
                        value[count] = y;
                        count++;
                    }
                }
            }

            listBox1.Items.Add("第一點座標 = (" + x + ", " + value[0] + ")");
            listBox1.Items.Add("第二點座標 = (" + x + ", " + value[1] + ")");
            listBox1.Items.Add("板手寬度 = " + (value[1] - value[0]).ToString());
            g2.DrawLine(new Pen(Color.Red), new Point(x, value[0]), new Point(x, value[1]));
            pictureBox2.Image = imgtwo;
        }

        private void button5_Click(object sender, EventArgs e)
        {
            // create filter
            BlobsFiltering filter = new BlobsFiltering();
            // configure filter
            filter.CoupledSizeFiltering = true;
            filter.MinWidth = 1;
            filter.MinHeight = 1;
            // apply the filter
            Bitmap dstImage = filter.Apply(tempImg);
            //pictureBox2.Image = dstImage;


            BlobCounterBase bc = new BlobCounter();
            bc.FilterBlobs = true;
            bc.MinWidth = 1;
            bc.MinHeight = 1;
            bc.ObjectsOrder = ObjectsOrder.Area;

            bc.ProcessImage(dstImage); // process binary image
            Blob[] blobs = bc.GetObjectsInformation();

            textBox1.Text = "Blob Count = " + bc.ObjectsCount.ToString();//總個數

            int totalarea = 0;
            for (int ii = 0; ii < bc.ObjectsCount; ii++)
            {
                totalarea = totalarea + blobs[ii].Area;
                listBox2.Items.Add("Blob[" + ii + "] = " + blobs[ii].Area.ToString());
            }
            listBox2.Items.Add("Total Area = " + totalarea);
        }
    }
}

C#-examination-b

題目要求:
掃描Bracket1圖片的 (a)兩個寬度與 (b)中間空隙之寬度
圖片:Bracket1.bmp

##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;
using AForge.Imaging.Filters;
using AForge.Imaging.Formats;

namespace examination_b
{
    public partial class Form1 : Form
    {
        Bitmap srcImg, tempImg, bwImg;

        int x = 400, y1 = 100, y2= 400;
        int[] y_value = new int[4];

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            srcImg = ImageDecoder.DecodeFromFile("Bracket1.bmp");
            tempImg = new Bitmap(srcImg);
            pictureBox1.Image = srcImg;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Graphics g = Graphics.FromImage(srcImg);
            g.DrawLine(new Pen(Color.Red), new Point(x, y1), new Point(x, y2));

            pictureBox1.Image = srcImg;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            Grayscale grayFilter = new Grayscale(0.2125, 0.7154, 0.0721);
            Bitmap grayImg = grayFilter.Apply(tempImg);

            OtsuThreshold otsuFilter = new OtsuThreshold();
            bwImg = otsuFilter.Apply(grayImg);

            pictureBox2.Image = bwImg;
        }

        private void button4_Click(object sender, EventArgs e)
        {
            int[,] point = new int[x+5, y2+5];
            int count = 0;

            for (int y = y1; y < y2; y++)
            {
                Color pixelColor = bwImg.GetPixel(x, y);
                point[x, y] = pixelColor.R;
            }

            for (int y = y1; y < y2; y++)
            {
                if (point[x, y] < 20)
                {
                    if (point[x, y] != point[x, y - 1] || point[x, y] != point[x, y + 1])
                    {
                        y_value[count] = y;
                        count++;
                        listBox1.Items.Add("(" + x + ", " + y + ")");
                    }
                }
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            Bitmap imgtwo = new Bitmap(bwImg);
            Graphics g2 = Graphics.FromImage(imgtwo);

            g2.DrawLine(new Pen(Color.Yellow), new Point(x, y_value[0]), new Point(x, y_value[1]));
            listBox2.Items.Add("上面寬度(Yellow) = " + (y_value[1] - y_value[0]).ToString());

            g2.DrawLine(new Pen(Color.Purple), new Point(x, y_value[1]), new Point(x, y_value[2]));
            listBox2.Items.Add("中間空隙(Purple) = " + (y_value[2] - y_value[1]).ToString());

            g2.DrawLine(new Pen(Color.Green), new Point(x, y_value[2]), new Point(x, y_value[3]));
            listBox2.Items.Add("上面寬度(Green) = " + (y_value[3] - y_value[2]).ToString());

            pictureBox2.Image = imgtwo;
        }
    }
}

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();
        }
    }
}

C#-examination-4

題目要求:

  • button1: 讀圖 lena 與 lena_2
  • button2: 求 lena 與 lena_2之差異 difference
  • button3: 將差異轉成灰階圖
  • button4: 利用影像增強手法將 button3 之差異強化
##ReadMore##

比較圖一:lena



比較圖二:lena_2


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;
using AForge.Imaging.Formats;
using AForge.Imaging.Filters;
using AForge.Video;
using System.Diagnostics;
using System.Drawing.Imaging;
using AForge.Math;

namespace examination_4
{
    public partial class exam4 : Form
    {
        Bitmap img1, img2, catchImg, grayImg;
        

        public exam4()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            openFileDialog1.Filter = "所有檔案(*.*)|*.*";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                img1 = ImageDecoder.DecodeFromFile(openFileDialog1.FileName);
                pictureBox1.Image = img1;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            openFileDialog2.Filter = "所有檔案(*.*)|*.*";
            if (openFileDialog2.ShowDialog() == DialogResult.OK)
            {
                img2 = ImageDecoder.DecodeFromFile(openFileDialog2.FileName);
                pictureBox2.Image = img2;
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            img1 = (Bitmap)pictureBox1.Image;
            img2 = (Bitmap)pictureBox2.Image;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            // 取兩圖長、寬最小值
            int imgWidth = Math.Min(img1.Width, img2.Width);
            int imgHeight = Math.Min(img1.Height, img2.Height);
            int minX = imgWidth;
            int minY = imgHeight;
            int maxX = 0;
            int maxY = 0;

            // 比較的 Pixel 範圍
            for (int x = 0; x < imgWidth; x++)
            {
                for (int y = 0; y < imgHeight; y++)
                {
                    // 比較兩圖 Pixel
                    if(img1.GetPixel(x,y).Equals(img2.GetPixel(x,y)))
                    {
                        // 相同 Pixel ,維持原圖                        
                    }
                    else
                    {
                        // 不相同

                        // 取差異圖最左上點
                        if (minX > x)
                            minX = x;
                        if (minY > y)
                            minY = y;

                        // 取差異圖最右下點
                        if (maxX < x)
                            maxX = x;
                        if (maxY < y)
                            maxY = y;
                    }
                }
            }
            
            catchDiff(minX, minY, maxX, maxY);
            drawDiffFrame(minX, minY, maxX, maxY);

            pictureBox1.Image = img1;
            pictureBox2.Image = img2;
        }

        // 補捉兩圖不同點於 pictureBox3
        private void catchDiff(int topLeft_X, int topLeft_Y, int bottomRight_X, int bottomRight_Y)
        {
            Crop cropFilter = new Crop(new Rectangle(topLeft_X - 5, topLeft_Y - 5, bottomRight_X - topLeft_X + 10, bottomRight_Y - topLeft_Y + 10));
            catchImg = cropFilter.Apply(img2);
            pictureBox3.Image = catchImg;
        }

        // 於原圖及比對圖畫出框,框出差異
        private void drawDiffFrame(int topLeft_X, int topLeft_Y, int bottomRight_X, int bottomRight_Y)
        {
            using (Graphics g = Graphics.FromImage(img1))
            {
                g.DrawRectangle(new Pen(Color.Red), topLeft_X - 6, topLeft_Y - 6, bottomRight_X - topLeft_X + 12, bottomRight_Y - topLeft_Y + 12);
            }
            using (Graphics g = Graphics.FromImage(img2))
            {
                g.DrawRectangle(new Pen(Color.Red), topLeft_X - 6, topLeft_Y - 6, bottomRight_X - topLeft_X + 12, bottomRight_Y - topLeft_Y + 12);
            }
        }

        // 影像灰階
        private void button4_Click(object sender, EventArgs e)
        {
            Grayscale grayFilter = new Grayscale(0.2125, 0.7154, 0.0721);
            grayImg = grayFilter.Apply(catchImg);
            pictureBox3.Image = grayImg;
        }

        // 續影像灰階,再影像強化處理
        private void button5_Click(object sender, EventArgs e)
        {
            Bitmap thsImg;
            Threshold thFilter = new Threshold(23);
            thsImg = thFilter.Apply(grayImg);
            pictureBox3.Image = thsImg;
        }

    }
}

C#-examination-3

題目要求:

  • 讀圖。
  • show 出圖之大小,包含 width and height。
  • show 出中間點 width/2 and height/2 之 RGB 值。
##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;
using AForge.Imaging.Filters;
using AForge.Imaging.Formats;

namespace examination_3
{
    public partial class exam3 : Form
    {

        Bitmap img;
        Color colorPixel;

        public exam3()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
        {
            
        }

        private void button1_Click(object sender, EventArgs e)
        {
             OpenFileDialog readImg = new OpenFileDialog();
             if (readImg.ShowDialog() == DialogResult.OK)
             {
                 img = new Bitmap(readImg.FileName);
                 pictureBox1.Image = img;

                 textBox1.Text = img.Width.ToString();
                 textBox2.Text = img.Height.ToString();

                 colorPixel = img.GetPixel(img.Width / 2, img.Height / 2);
                 textBox3.Text = colorPixel.R.ToString();
                 textBox4.Text = colorPixel.G.ToString();
                 textBox5.Text = colorPixel.B.ToString();

             }
        }
    }
}

C#-examination-2

題目要求:
  • button1: 做積分
  • steps數目10000
  • show出結果與執行時間(耗時)
##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 System.Diagnostics;

namespace examination_2
{
    public partial class exam2 : Form
    {

        Stopwatch stopWatch = new Stopwatch();

        public exam2()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            // Start Watch
            stopWatch.Reset();
            stopWatch.Start();

            // Integration
            int steps = 10000;
            double ans = 0;
            double x, fx;
            double en = 4 * Math.PI;
            double bn = 0;
            double parti = (en - bn) * 1 / steps;

            for (int i = 0; i < steps; i++)
            {
                x = bn + parti * i;
                fx = x * x * x * Math.Sin(2 * x) * Math.Cos(x);
                ans = ans + fx * parti;
            }

            // Stop Watch
            stopWatch.Stop();

            // Show timesapn and Answer
            TimeSpan ts = stopWatch.Elapsed;
            textBox1.Text = ts.ToString();
            textBox2.Text = ans.ToString();
            
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {

        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {

        }
    }
}

C#-examination-1

題目要求:
  1. 做 button1 → 讀圖。
  2. 做 button2 → 從左上角劃一綠線,至右下角。
  3. 做 button3 → 中間部位畫一50X150之紅色四邊形。
  4. 做 button4 → 存檔。

##ReadMore##

測試圖檔:https://sites.google.com/site/p501labsite/microsoft-virtual-studio/lena.png?attredirects=0&d=1


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;
using AForge.Imaging.Filters;
using AForge.Imaging.Formats;


namespace examination_1
{
    public partial class exam1 : Form
    {
        //statement
        Bitmap img_L, img_R;
        Color colorPixel;
        int[,] maR = new int[1024, 1024];
        int[,] maG = new int[1024, 1024];
        int[,] maB = new int[1024, 1024];

        public exam1()
        {
            InitializeComponent();
        }

        //Read File
        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog readImg = new OpenFileDialog();
            if (readImg.ShowDialog() == DialogResult.OK)
            {
                img_L = new Bitmap(readImg.FileName);
                img_R = img_L;
                pictureBox1.Image = img_L;
                pictureBox2.Image = img_L;

                // 儲存原圖 colorPixel 
                for (int i = 0; i < img_L.Width; i++)
                {
                    for (int j = 0; j < img_L.Height; j++)
                    {
                        colorPixel = img_L.GetPixel(i, j);
                        maR[i, j] = colorPixel.R;
                        maG[i, j] = colorPixel.G;
                        maB[i, j] = colorPixel.B;
                    }
                }
            }
        }

        //Diagonal Top-left to Bottom-right
        private void button2_Click(object sender, EventArgs e)
        {
            // 對角線之 colorPixel
            for (int i = 0; i <= img_L.Height; i++)
            {
                maR[i, i] = 0;
                maG[i, i] = 0;
                maB[i, i] = 0;
            }

            // paint diagonal
            for (int i = 0; i < img_L.Width; i++)
            {
                for (int j = 0; j < img_L.Height; j++)
                {
                    Color diagonalPixel = Color.FromArgb(maR[i, j], maG[i, j], maB[i, j]);
                    img_R.SetPixel(i, j, diagonalPixel);
                }
            }
            pictureBox2.Image = img_R;

        }

        //Rectangle 50 x 150
        private void button3_Click(object sender, EventArgs e)
        {
            int drawWidth = 50;
            int drawHeight = 150;

            // 中間繪圖點
            int originX = img_L.Width / 2 - drawWidth / 2;
            int originY = img_L.Height / 2 - drawHeight / 2;

            for (int i = originX; i <= originX + drawWidth; i++)
            {
                for (int j = originY; j <= originY + drawHeight; j++)
                {
                    maR[i, j] = 255;
                    maG[i, j] = 0;
                    maB[i, j] = 0;
                }
            }

            // paint rectangle
            for (int i = 0; i < img_L.Width; i++)
            {
                for (int j = 0; j < img_L.Height; j++)
                {
                    Color rectanglePixel = Color.FromArgb(maR[i, j], maG[i, j], maB[i, j]);
                    img_R.SetPixel(i, j, rectanglePixel);
                }
            }
            pictureBox2.Image = img_R;
        }

        //Save File
        private void button4_Click(object sender, EventArgs e)
        {
            saveFileDialog1.FileName = @"img.bmp";
            saveFileDialog1.Filter = "Bitmap File(*.bmp) | *.bmp";
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                img_R.Save(saveFileDialog1.FileName);
            }

        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}