# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'qt_and_cv/mainWindow_CVtest.ui'
#
# Created by: PyQt5 UI code generator 5.15.2
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again.  Do not edit this file unless you know what you are doing.


import sys
import cv2
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5 import QtWidgets, QtCore
import json
import icos

# flat 函数用于将多维list转为一维list
def flat(l):
    for k in l:
        if not isinstance(k, (list, tuple)):
            yield k
        else:
            yield from flat(k)


class Ui_Form(QWidget):
    f_in, f_out, rate = "", "", 1
    dict_path = {"f_in": "", "f_out": "", "rate": 1}
    isbusy = False
    try:
        with open(".path.json") as f:
            dict_path = json.loads(f.read())
    except:
        pass
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(607, 413)
        self.graphicsView = QtWidgets.QLabel(Form)
        self.graphicsView.setGeometry(QtCore.QRect(120, 90, 480, 320))
        self.graphicsView.setObjectName("graphicsView")
        self.layoutWidget = QtWidgets.QWidget(Form)
        self.layoutWidget.setGeometry(QtCore.QRect(10, 10, 591, 69))
        self.layoutWidget.setObjectName("layoutWidget")
        self.verticalLayout = QtWidgets.QVBoxLayout(self.layoutWidget)
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout.setObjectName("verticalLayout")
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.pushButton = QtWidgets.QPushButton(self.layoutWidget)
        self.pushButton.setObjectName("pushButton")
        self.horizontalLayout.addWidget(self.pushButton)
        self.lineEdit = QtWidgets.QLineEdit(self.layoutWidget)
        self.lineEdit.setObjectName("lineEdit")
        self.horizontalLayout.addWidget(self.lineEdit)
        self.verticalLayout.addLayout(self.horizontalLayout)
        self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.pushButton_2 = QtWidgets.QPushButton(self.layoutWidget)
        self.pushButton_2.setObjectName("pushButton_2")
        self.horizontalLayout_2.addWidget(self.pushButton_2)
        self.lineEdit_2 = QtWidgets.QLineEdit(self.layoutWidget)
        self.lineEdit_2.setObjectName("lineEdit_2")
        self.horizontalLayout_2.addWidget(self.lineEdit_2)
        self.verticalLayout.addLayout(self.horizontalLayout_2)
        self.layoutWidget1 = QtWidgets.QWidget(Form)
        self.layoutWidget1.setGeometry(QtCore.QRect(10, 90, 101, 100))
        self.layoutWidget1.setObjectName("layoutWidget1")
        self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.layoutWidget1)
        self.verticalLayout_2.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.label = QtWidgets.QLabel(self.layoutWidget1)
        self.label.setObjectName("label")
        self.verticalLayout_2.addWidget(self.label)
        self.lineEdit_3 = QtWidgets.QLineEdit(self.layoutWidget1)
        self.lineEdit_3.setObjectName("lineEdit_3")
        self.verticalLayout_2.addWidget(self.lineEdit_3)
        self.radioButton = QtWidgets.QRadioButton(self.layoutWidget1)
        self.radioButton.setObjectName("radioButton")
        self.verticalLayout_2.addWidget(self.radioButton)
        self.pushButton_3 = QtWidgets.QPushButton(self.layoutWidget1)
        self.pushButton_3.setObjectName("pushButton_3")
        self.verticalLayout_2.addWidget(self.pushButton_3)

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "OLED128x64 视频取模器v1.0"))
        self.pushButton_3.setText(_translate("Form", "开始"))
        self.pushButton.setText(_translate("Form", "选择输入文件"))
        self.pushButton_2.setText(_translate("Form", "选择输出路径"))
        self.label.setText(_translate("Form", "采样间隔(帧)"))
        self.lineEdit_3.setText(_translate("Form", "1"))
        self.radioButton.setText(_translate("Form", "是否取反"))

        self.pushButton_3.clicked.connect(self.run)
        self.pushButton.clicked.connect(self.load_video)
        self.pushButton_2.clicked.connect(self.output_setpath)

        self.lineEdit.setText(self.dict_path["f_in"])
        self.f_in, self.f_out = self.dict_path["f_in"], self.dict_path["f_out"]
        self.rate = int(self.dict_path["rate"])
        self.lineEdit_2.setText(self.dict_path["f_out"])
        self.lineEdit_3.setText(str(self.dict_path["rate"]))

        Form.setFixedSize(607,413)

    def load_video(self):
        f_name, _ = QFileDialog.getOpenFileName(self, "打开文件", ".", "图像文件(*.mp4 *.wav *.flv)")
        self.lineEdit.setText(f_name)
        self.f_in = self.lineEdit.text()
        pass

    def output_setpath(self):
        dialog = QFileDialog()
        dialog.setFileMode(QFileDialog.AnyFile)
        dialog.setFilter(QDir.Files)

        if dialog.exec():
            filenames = dialog.selectedFiles()
            self.lineEdit_2.setText(filenames[0])
            self.f_out = self.lineEdit_2.text()

    def run(self):
        if self.isbusy:
            QMessageBox.about(self, "提示", "正在运行 ")
            return
        try :
            self.rate = int(self.lineEdit_3.text())
            self.dict_path["f_in"] = self.f_in
            self.dict_path["f_out"] = self.f_out
            self.dict_path["rate"] = str(self.rate)
            with open(".path.json", "w") as f:
                f.write(json.dumps(self.dict_path))
            self.isbusy = True
            self.gen(self.f_in, self.f_out, self.rate)
        except: pass
            # reply2 = QMessageBox.warning(self, "提示", "输入不正确 ", QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
        self.isbusy = False
    def gen(self, file_in, file_out, rate):
        cap = cv2.VideoCapture(file_in)
        f_out = open(file_out, "wb")
        rate = rate
        cnt = 0
        while cap.isOpened():
            ret, frame = cap.read()
            print('frame.shape:', frame.shape)
            # cv2.imshow('frame', frame)
            key = cv2.waitKey(delay=0)
            img = cv2.resize(frame, (128, 64))
            gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
            ret, img_out = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
            point_map = list(flat(img_out.tolist()))
            for i in range(len(point_map)):
                if self.radioButton.isChecked():
                    point_map[i] = 1 if point_map[i] == 0 else 0
                else:
                    point_map[i] = 0 if point_map[i] == 0 else 1
            bt_array = []
            for k in range(8):
                for j in range(128):
                    bt = 0
                    for i in range(8):
                        bt = bt * 2 + point_map[k * 128 * 8 + 128 * (7 - i) + j]
                    bt_array.append(bt)
            if cnt % rate == 0:
                f_out.write(bytearray(bt_array))
                # cv2.imshow('frame', frame)
                show = cv2.resize(frame, (480, 320))
                show = cv2.cvtColor(show, cv2.COLOR_BGR2RGB)
                showImage = QImage(show.data, show.shape[1], show.shape[0], QImage.Format_RGB888)
                self.graphicsView.setPixmap(QPixmap.fromImage(showImage))
                self.graphicsView.show()
            cnt += 1

        f_out.close()
        cap.release()
        cv2.destroyAllWindows()
        exit()



