# Applications of Image Processing and Deep learning on bridge game analysis
<font size=2>指導教授:嚴力行</font>
<font size=2>專題成員:賴沛冠,陳芃,李泓賢</font>
## Introduction
  By collecting card data on the Internet and performing algorithms for machine learning, we can establish an ideal set of bidding and playing methods, and then assisted by identifying cards system so that they can be used on the actual card table without limit to computer vs player or computer vs computer.
## Environment Setting
### 影像辨識系統
#### 下載、安裝與執行
1. Download the card identify code on GitHub
```
$ git clone https://github.com/pbmartins/card-recognition.git
```
2. Compilation
```
$ cmake .
$ make
```
3. 本次專題是在虛擬機(Oracle VM Virtual Box)上執行,因此需要將主機的攝影機連接至虛擬機上
**以下動作會在本機(windows 10系統)上執行**
步驟如下:
```
a. 下載 Virtual Box 的 Extension pack (下載對應VM之版本)
```
Link : http://download.virtualbox.org/virtualbox/
```
b. 打開 Virtual Box 的"喜好設定",並添加剛才下載的功能包
```

```
c. 待安裝完畢後,開啟cmd(Windows 的命令提示字元)並輸入以下指令
$ cd c:\Program Files\Oracle\VirtualBox //移動至 VirtualBox 的資料夾
$ VBoxManage list webcams //列出系統中的webcam
```
執行結果 :

```
$ VboxManage controlvm "你的虛擬機名稱" webcam attach .1
//將webcam連結至對應的虛擬機
```
4. 在虛擬機中執行程式
```
./card_recognition
```
執行結果 :

完整執行影片 : https://youtu.be/R4_akRpuzHQ
#### 結果分析
目前已達到可以成功辨識單一撲克牌之花色及點數,惟有幾點仍須改進
1. 在辨識黑桃(Spade)時,程式容易將其與形狀相似的梅花(Club)混淆

2. 若撲克牌重疊,程式便無法辨識 (目前著重解決的項目)
### 安裝 OpenCV 與建置 C++ 編譯環境
:::info
**注意:** 只適用在 Linux 以及 MacOS 系統上,Windows 不適用喔!
:::
建置 OpenCV
1. 下載 OpenCV 的相依套件
```
$ sudo apt-get install build-essential cmake git libgtk2.0-dev pkg-config libavcodec-dev libavformat-dev libswscale-dev
$ sudo apt-get install python3.5-dev python3-numpy libtbb2 libtbb-dev
$ sudo apt-get install libjpeg-dev libpng-dev libtiff5-dev libjasper-dev libdc1394-22-dev libeigen3-dev libtheora-dev libvorbis-dev libxvidcore-dev libx264-dev sphinx-common libtbb-dev yasm libfaac-dev libopencore-amrnb-dev libopencore-amrwb-dev libopenexr-dev libgstreamer-plugins-base1.0-dev libavutil-dev libavfilter-dev libavresample-dev
2. 下載 OpenCV
```
$ sudo su
$ cd /opt
$ git clone https://github.com/Itseez/opencv.git
$ git clone https://github.com/Itseez/opencv_contrib.git
3. 編譯與安裝
```
$ cd opencv
$ mkdir release
$ cd release
$ mkdir my_build_dir
$ cd my_build_dir
$ cmake -D BUILD_TIFF=ON -D WITH_CUDA=OFF -D ENABLE_AVX=OFF -D WITH_OPENGL=OFF -D WITH_OPENCL=OFF -D WITH_IPP=OFF -D WITH_TBB=ON -D BUILD_TBB=ON -D WITH_EIGEN=OFF -D WITH_V4L=OFF -D WITH_VTK=OFF -D BUILD_TESTS=OFF -D BUILD_PERF_TESTS=OFF -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local -D OPENCV_EXTRA_MODULES_PATH=/opt/opencv_contrib/modules /opt/opencv/
$ make -j4
$ make install
$ ldconfig
$ exit
$ cd ~
---
## Experiment
1. Dataset of Bridge games
Resource: http://www.allevybridge.com/allevy/computerbridge/
ex. [2016](http://www.allevybridge.com/allevy/computerbridge/2016scores.html) [2017](http://www.allevybridge.com/allevy/computerbridge/2017_scores6.html)

Resource2: https://www.bridgebase.com/vugraph_archives/vugraph_archives.php


參考網站 : https://www.chainnews.com/zh-hant/articles/264998147324.htm
在2019年AAMAS 2019 的 140 篇入選論文中,其中有一篇關於不完全信息博弈遊戲——橋牌遊戲的論文——《Competitive Bridge Bidding with Deep Neural Networks》。
論文主要研究了在橋牌遊戲中,基於神經網絡構建叫牌系統的方法。
其中所使用到的資料集便是從Vugraph Project中蒐集之世界橋牌比賽的完整過程
我們需要寫幾個爬蟲程式來抓取這些網路上的卡牌Data,因為一個網站提供的樣本數量不會大到可以提供機器學習,因此我們得找很多不同的網站,所以需要許多不同的爬蟲程式來抓取HTML的資料
2. Mechine learning applicates on Bridge game
-not be done yet
---
## Mnist數字集訓練資料,用以預測手寫數字 (機器學習實作練習)
下載Mnist資料集:

In[1,2]:匯入所需模組
In[3,4]:讀取mnist資料
In[5]:將features(數字影像特徵值)使用reshape轉換
(原本28*28的影像,轉為784個float數字),二維轉一維的概念
In[6]:將features標準化,可以提高模型預測的準確度

---------------------------------------------------------------

In[7,8]:將訓練資料與測試資料的label進行One-hot encoding
In[9]:讀取第0筆訓練資料(顯示是5)
In[10]:檢視one-hot encoding 後的結果,會在第六個位置上為1,其他位置上為0
---------------------------------------------------------------

X_train_image為訓練影像,y_train_label為影像實際Label值
---------------------------------------------------------------

X_test_image為測試影像,y_test_label為影像實際Label值
---------------------------------------------------------------

多層感知器模型,輸入層(x)共有28x28=784個神經元,Hidden layers共有256層;輸出層共有10個神經元

建立多層感知器模型
In[11]:匯入所需模組
In[12]:建立線性堆疊模型,後續只需使用model.add()方法,將各神經網路層加入模型
In[13]:建立輸出層與隱藏層,使用model.add加入Dense神經網路層(上層與下層神經元都完全連結)
In[14]:建立輸出層,共有10層神經元,對應到0~9十個數字,使用softmax函數進行轉換

隱藏層共256個神經元,因為輸出層和隱藏層是一起建立的,所以沒有顯示輸入層
輸出層共10個神經元
---------------------------------------------------------------

訓練資料
```
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
```
loss設定損失函數(loss function),在深度學習使用cross_entropy
```
train_history = model.fit(x=x_Train_norm, y=y_TrainOneHot, validation_split=0.2, epochs=10, batch_size=200, verbose=2)
```
x=x_Train_norm: features數字影像的特徵值
y=y_TrainOneHot: label數字影像真實值
validation_split: Keras將80%作為訓練資料,20%作為驗證資料
epochs=10: 執行10次訓練週期(每次訓練會讓正確率提高)
batch_size=200: 每一批次訓練200筆資料
verbose=2: 顯示訓練過程
---------------------------------------------------------------

簡易查看預測結果
In[21]:評估模型預測準確率97.8%
In[23]:使用model.predict_classes,輸入測試的數字影像進行預測
並且將結果存在prediction變數
In[24]:查看預測的前幾筆資料(7,2,1...)可參照下面圖片,符合預測結果
---------------------------------------------------------------

藉由上述建立的多層感知器模型,將資料進行預處理就能進行預測(辨識)這些手寫數字
可見圖片中第9張圖片,Lable值為5,但預測結果卻是6。
由此可知機器學習後的結果還是有可能有預測錯誤
## Conclusion
  我們目前做到的部分是: 完成卡牌辨識、蒐集到比賽的卡牌紀錄(包含出牌以及叫牌)、以及一些機器學習基本的理論以及簡單的實作。
  目前的階段目標為:
    1.克服扇形攤牌時的卡牌辨識
    2.將網路上的卡面數據抓下來整理成資料庫並運行Mechine learning
    3.比較不同神經網路架構的正確性
    4.將Opencv取得之現場比賽卡面資訊擷取,並投入神經網路給予推薦指令
    5.彙整研究結果
  在這個為期兩個月的暑假,我們會努力按照階段目標來完成這個專題。
## Reference [close]
---
- [TensorFlow 基礎篇〈上〉](https://fgc.stpi.narl.org.tw/activity/videoDetail/4b1141305d9cd231015d9d07dbe1002a?fbclid=IwAR0fP8Jprd2ZxioI2d2xfX_eYCMJaNdsOB0SSH-qym9MiDDJNvsy-_D0bNA)
- [OpenCV-Playing-Card-Detector](https://github.com/EdjeElectronics/OpenCV-Playing-Card-Detector?fbclid=IwAR1zpc5hsUh-Su5qq1oyFltJqB2UuPfO9SAWjSiytFpJrEmWqU7CfiQfPVo)
- [Playing Card Detection Using OpenCV-Python on the Raspberry Pi 3 + PiCamera](https://www.youtube.com/watch?v=m-QPjO-2IkA&fbclid=IwAR3r7iv20zohHJk5fArGLHUKCJwLqSO1q0k5UVlDJ3xAQZ-f3xf94LV5w1Q)
- [card-recognition](https://github.com/pbmartins/card-recognition?fbclid=IwAR14LtWm0ix7ykkH3wgWbvZKwhbci1wmVsgKqi1fRNqFniIj-7NyNpfhIyk)
- [Machine Learning for bridge by NTU](https://drive.google.com/file/d/1JmoDV3AglmqQBqqnsnk7OjM9UVKgvEWU/view?usp=sharing)
- [Enabling Webcam in VirtualBox Guest OS on Windows Host](https://scribles.net/using-webcam-in-virtualbox-guest-os-on-windows-host/)
- [Pyramid Dilated Deeper ConvLSTM for Video Salient Object Detection, ECCV, 2018](https://github.com/shenjianbing/PDB-ConvLSTM)
- [Learning Unsupervised Video Object Segmentation through VisualAttention](https://github.com/wenguanwang/AGS)
- [Shifting More Attention to Video Salient Object Detection](https://github.com/wenguanwang/DAVSOD)
- [See More, Know More: Unsupervised Video Object Segmentation with Co-Attention Siamese Networks](https://github.com/carrierlxk/COSNet)
- 實體書籍:TensorFlow+Keras深度學習人工智慧實務應用
