#  -*- coding: UTF-8 -*-

# MindPlus
# Python
import sys
sys.path.append("/root/mindplus/.lib/thirdExtension/nick-pytesseract-thirdex")
from pinpong.board import Board, Pin
from pinpong.extension.unihiker import *
import time
import cv2
import pytesseract
from PIL import Image, ImageFont, ImageDraw
import os
import numpy as np

# 初始化UNIHIKER开发板
Board().begin()

# 定义一个绘制中文字符的函数
def drawChinese(text, x, y, size, r, g, b, a, img):
    font = ImageFont.truetype("HYQiHei_50S.ttf", size)
    img_pil = Image.fromarray(img)
    draw = ImageDraw.Draw(img_pil)
    draw.text((x, y), text, font=font, fill=(b, g, r, a))
    frame = np.array(img_pil)
    return frame

# 配置Tesseract命令路径
pytesseract.pytesseract.tesseract_cmd = r'/usr/bin/tesseract'

# 打开摄像头
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 240)  # 设置摄像头宽度
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 320)  # 设置摄像头高度
cap.set(cv2.CAP_PROP_BUFFERSIZE, 1)  # 设置缓冲区大小
cv2.namedWindow('cvwindow', cv2.WND_PROP_FULLSCREEN)  # 创建OpenCV窗口
cv2.setWindowProperty('cvwindow', cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)  # 设置窗口为全屏模式

# 等待摄像头准备就绪
while not cap.isOpened():
    continue

print("start!")
ShiBieNaRong = ''
img_word1 = ''
img_word2 = ''

# 主循环，捕获摄像头图像并显示
while True:
    cvimg_success, img_src = cap.read()  # 读取摄像头图像
    cvimg_h, cvimg_w, cvimg_c = img_src.shape
    cvimg_w1 = cvimg_h * 240 // 320
    cvimg_x1 = (cvimg_w - cvimg_w1) // 2
    img_src = img_src[:, cvimg_x1:cvimg_x1 + cvimg_w1]
    img_src = cv2.resize(img_src, (240, 320))  # 调整图像大小
    cv2.imshow('cvwindow', img_src)  # 在窗口中显示图像
    key = cv2.waitKey(5)  # 等待按键事件

    if key & 0xFF == ord('b'):  # 按下'b'键退出程序
        print("退出视频")
        break
    elif key & 0xFF == ord('a'):  # 按下'a'键捕获图像并识别中文字符
        ShiBieNaRong = []
        try:
            if not os.path.exists("/root/image/pic/"):  # 检查文件夹是否存在
                print("The folder does not exist, created automatically")
                os.system("mkdir -p /root/image/pic/")  # 创建文件夹
        except IOError:
            print("IOError, created automatically")
            break

        cv2.imwrite("/root/image/pic/image.png", img_src)  # 保存捕获的图像
        time.sleep(0.2)
        img = Image.open('/root/image/pic/image.png')  # 打开图像
        ShiBieNaRong = pytesseract.image_to_string(img, lang='chi_sim')[0:2]  # 识别中文字符
        print(ShiBieNaRong)

    # 在图像上绘制识别到的中文字符
    img_src = drawChinese(text=str(ShiBieNaRong), x=10, y=20, size=25, r=50, g=200, b=0, a=0, img=img_src)
    cv2.imshow('cvwindow', img_src)  # 在窗口中显示带有中文字符的图像

cap.release()  # 释放摄像头
cv2.destroyAllWindows()  # 关闭所有OpenCV窗口
