import tensorflow.keras as keras
from PIL import Image, ImageOps, ImageFont , ImageDraw

import numpy as np
import cv2

ESC = 27

# 顯示判斷結果
font = ImageFont.truetype('msjhbd.ttc', 40)
fillColor = (255, 0, 0)

# 選擇攝影機
cap = cv2.VideoCapture(0)

np.set_printoptions(suppress = True)

# 請自行修改 h5 檔案位置
model = keras.models.load_model('keras_model.h5')

data = np.ndarray(shape=(1, 224, 224, 3), dtype = np.float32)

while cap.isOpened():
    ret, frame = cap.read()  
    image = Image.fromarray(frame)
    size = (224, 224)
    image = ImageOps.fit(image, size, Image.ANTIALIAS)

    image_array = np.asarray(image)
    normalized_image_array = (image_array.astype(np.float32) / 127.0) - 1
    data[0] = normalized_image_array

    # 預測結果
    prediction = model.predict(data)    

    # 顯示結果，請將 label 內容依照次序排列
    maxindex = np.argmax(prediction)    # 找出機率最大的輸出
    
    if prediction.max() > 0.5:    # 如果最大的機率都 < 0.5 就當作無法判斷       
        if maxindex == 0:
            print("剪刀")
            showtext = "剪刀"
        elif maxindex == 1:
            print("石頭")
            showtext = "石頭"
        elif maxindex == 2:
            print("布")
            showtext = "布"
        elif maxindex == 3:
            print("沒有")      
            showtext = "沒有"
    else:
        print('無法辨識')

    print(prediction)
    
    # 在圖上顯示結果
    img_PIL = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
    draw = ImageDraw.Draw(img_PIL)
    draw.text((0,0), showtext, font = font, fill = fillColor)
    frame = cv2.cvtColor(np.asarray(img_PIL), cv2.COLOR_RGB2BGR)
    cv2.imshow('frame', frame)
        
    # 按 ESC 離開
    if cv2.waitKey(1) == ESC:
        break

# 釋放攝影機
cap.release()

# 關閉所有 OpenCV 視窗
cv2.destroyAllWindows()
