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

# Form implementation generated from reading ui file 'Demo7.ui'
#
# Created by: PyQt5 UI code generator 5.15.1
#
# 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.


from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import *
import cv2
import xlwt,os
from pylab import mpl
mpl.rcParams['font.sans-serif'] = ['SimHei']
global point1, point2, img, r,c,s1
from pylab import mpl
from decimal import *
import threading
import numpy as np
from xlrd import *
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtCore import QCoreApplication

mpl.rcParams['font.sans-serif'] = ['SimHei']


def lwdt(img_A):
    thresh_A_copy = img_A.copy()  # 复制thresh_A到thresh_A_copy
    thresh_B = np.zeros(img_A.shape, np.uint8)  # thresh_B大小与A相同，像素值为0

    kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))  # 3×3结构元

    count = []  # 为了记录连通分量中的像素个数
    amount = 6
    result = 0
    while amount:
        Xa_copy, Ya_copy = np.where(thresh_A_copy > 0)  # thresh_A_copy中值为255的像素的坐标
        thresh_B[Xa_copy[0]][Ya_copy[0]] = 255  # 选取第一个点，并将thresh_B中对应像素值改为255

        # 连通分量算法，先对thresh_B进行膨胀，再和thresh_A执行and操作（取交集）
        for i in range(300):
            dilation_B = cv2.dilate(thresh_B, kernel, iterations=10)
            thresh_B = cv2.bitwise_and(img_A, dilation_B)

        # 取thresh_B值为255的像素坐标，并将thresh_A_copy中对应坐标像素值变为0
        Xb, Yb = np.where(thresh_B > 0)
        thresh_A_copy[Xb, Yb] = 0

        # 显示连通分量及其包含像素数量
        count.append(len(Xb))
        if len(count) == 0:
            print("无连通分量")
        if len(count) == 1:
            result = result + 1
            print("第1个连通分量为{}".format(count[0]))
        if len(count) >= 2:
            if (count[-1] - count[-2]) > 100:
                result = result + 1
            print("第{}个连通分量为{}".format(len(count), count[-1] - count[-2]))
        amount = amount - 1


    return result

def detection(img0):
    # 读入图片
    global img, r, c, s1
    img00 = img
    b, g, r = cv2.split(img0)
    img1 = cv2.merge([r, g, b])
    # rgb转hsv
    img0 = cv2.cvtColor(img1, cv2.COLOR_BGR2HSV)
    img2 = img0[:, :, 1]

    # 图片处理
    def bi_demo(image, d, m, n):  # 双边滤波
        dst = cv2.bilateralFilter(image, d, m, n)
        return dst

    kernel = np.ones((6, 6), dtype=np.uint8)
    erosion = cv2.erode(img2, kernel, 16)
    img2 = cv2.dilate(img2, kernel, 25)
    img2 = cv2.morphologyEx(img2, cv2.MORPH_CLOSE, kernel, 19)

    img3 = bi_demo(img2, 9, 10, 19)

    def detect(image):  ###裂纹检测
        start = 0
        l = image.shape[0] // 20
        for i in range(0, l + 1, 1):
            end = start + 20
            if i == l:
                imag = image[start:image.shape[0], :]
            else:
                imag = image[start:end, :]
            max1 = max(max(row) for row in imag)

            for y in range(0, imag.shape[0], 1):
                for x in range(0, imag.shape[1], 1):
                    if (max1 * 8 // 9 < imag[y, x] < 180):
                        imag[y, x] = 255
                    else:
                        imag[y, x] = 0
            if i == l:
                image[start:image.shape[0], :] = imag[:, :]
            else:
                image[start:end, :] = imag[:, :]
            start = end

    detect(img3)

    # 面积计算
    def area(image, image0):  ###计算裂纹所占像素
        count = 0
        all = 0
        for y in range(0, image0.shape[0], 1):
            for x in range(0, image0.shape[1], 1):
                if (image0[y, x] == 0):
                    all = all + 1
        img4 = img[:, :, 0]
        for y in range(0, image.shape[0], 1):
            for x in range(0, image.shape[1], 1):
                if (image[y, x] == 255):
                    count = count + 1
        getcontext().prec = 4
        s = Decimal(count) / Decimal((img4.shape[0] * img4.shape[1] - all))
        return count, s

    count, s = area(img3, img2)
    str = '要显示的字符串'

    print("舌像裂纹面积为：{} 像素点， 占整个舌头像素的：{}".format(count, s))

    result = lwdt(img3)
    r = result
    c = count
    s1 = s
    mainMindow.shows(img3)
    mainMindow.textEdit_4.setText(mainMindow.file)
    mainMindow.textEdit_3.setText("{}".format(s1))
    mainMindow.textEdit_2.setText("{}".format(c))
    mainMindow.textEdit.setText("{}".format(r))
    # file_name = file.split('.')[0]
    # os.makedirs("./new/{}".format(file_name))
    # cv2.imwrite("./new/{}/{}".format(file_name, file), img00)
    # cv2.imwrite("./new/{}/{}".format(file_name, "0.jpg"), img0)
    # cv2.imwrite("./new/{}/{}".format(file_name, "1.jpg"), img1)
    # cv2.imwrite("./new/{}/{}".format(file_name, "2.jpg"), img2)
    # cv2.imwrite("./new/{}/{}".format(file_name, "3.jpg"), img3)

def on_mouse(event, x, y, flags, param):
    global  point1, point2, img
    img2 = img.copy()
    if event == cv2.EVENT_LBUTTONDOWN:  # 左键点击
        point1 = (x, y)

        # 按住左键拖曳
        cv2.rectangle(img2, point1, (x, y), (0, 255, 0), 1)
        cv2.namedWindow("image", 0)
        cv2.imshow('image', img2)
    elif event == cv2.EVENT_MOUSEMOVE and (flags & cv2.EVENT_FLAG_LBUTTON):  # 按住左键拖曳
        cv2.rectangle(img2, point1, (x, y), (0, 255, 0), 1)
        cv2.imshow('image', img2)
    elif event == cv2.EVENT_LBUTTONUP:  # 左键释放
        point2 = (x, y)
        cv2.rectangle(img2, point1, point2, (0, 0, 255), 1)
        cv2.imshow('image', img2)
        min_x = min(point1[0], point2[0])
        min_y = min(point1[1], point2[1])
        width = abs(point1[0] - point2[0])
        height = abs(point1[1] - point2[1])
        cut_img = img[min_y:min_y + height, min_x:min_x + width]
        detection(cut_img)


class Ui_mainWindow(QMainWindow):

    def setupUi(self, mainWindow):
        mainWindow.setObjectName("mainWindow")
        mainWindow.setEnabled(True)
        mainWindow.resize(958, 627)
        self.centralwidget = QtWidgets.QWidget(mainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(630, 380, 91, 51))
        font = QtGui.QFont()
        font.setFamily("微软雅黑")
        font.setPointSize(12)
        self.label.setFont(font)
        self.label.setStyleSheet("color: rgb(0, 0, 0);")
        self.label.setObjectName("label")
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(630, 430, 201, 51))
        font = QtGui.QFont()
        font.setFamily("微软雅黑")
        font.setPointSize(12)
        self.label_2.setFont(font)
        self.label_2.setStyleSheet("color: rgb(0, 0, 0);")
        self.label_2.setObjectName("label_2")
        self.label_3 = QtWidgets.QLabel(self.centralwidget)
        self.label_3.setGeometry(QtCore.QRect(630, 480, 221, 51))
        font = QtGui.QFont()
        font.setFamily("微软雅黑")
        font.setPointSize(12)
        self.label_3.setFont(font)
        self.label_3.setStyleSheet("color: rgb(0, 0, 0);")
        self.label_3.setObjectName("label_3")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(640, 100, 93, 28))
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(12)
        self.pushButton.setFont(font)
        self.pushButton.setStyleSheet("color: rgb(0, 0, 0);")
        self.pushButton.setObjectName("pushButton")
        self.graphicsView = QtWidgets.QGraphicsView(self.centralwidget)
        self.gridLayout = QtWidgets.QGridLayout()
        self.gridLayout.setObjectName("gridLayout")
        self.gridLayout.addWidget(self.graphicsView , 10, 30, 601, 541)
        self.graphicsView.setGeometry(QtCore.QRect(10, 30, 601, 541))
        self.graphicsView.setObjectName("graphicsView")
        # self.lb = MyLabel(self)
        # self.lb.setGeometry(QRect(10, 30, 601, 541))
        self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_2.setGeometry(QtCore.QRect(630, 50, 111, 31))
        font = QtGui.QFont()
        font.setFamily("微软雅黑")
        font.setPointSize(12)
        self.pushButton_2.setFont(font)
        self.pushButton_2.setMouseTracking(False)
        self.pushButton_2.setStyleSheet("color: rgb(0, 0, 0);")
        self.pushButton_2.setObjectName("pushButton_2")
        self.textEdit = QtWidgets.QTextEdit(self.centralwidget)
        self.textEdit.setEnabled(False)
        self.textEdit.setGeometry(QtCore.QRect(720, 390, 104, 31))
        self.textEdit.setStyleSheet("\n"
"background-color: rgb(255, 255, 255);")
        self.textEdit.setObjectName("textEdit")
        self.textEdit_2 = QtWidgets.QTextEdit(self.centralwidget)
        self.textEdit_2.setEnabled(False)
        self.textEdit_2.setGeometry(QtCore.QRect(820, 440, 111, 31))
        self.textEdit_2.setStyleSheet("\n"
"background-color: rgb(255, 255, 255);")
        self.textEdit_2.setObjectName("textEdit_2")
        self.textEdit_3 = QtWidgets.QTextEdit(self.centralwidget)
        self.textEdit_3.setEnabled(False)
        self.textEdit_3.setGeometry(QtCore.QRect(840, 490, 104, 31))
        self.textEdit_3.setStyleSheet("\n"
"background-color: rgb(255, 255, 255);")
        self.textEdit_3.setObjectName("textEdit_3")
        self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_3.setGeometry(QtCore.QRect(630, 160, 111, 31))
        font = QtGui.QFont()
        font.setFamily("微软雅黑")
        font.setPointSize(12)
        self.pushButton_3.setFont(font)
        self.pushButton_3.setMouseTracking(True)
        self.pushButton_3.setStyleSheet("color: rgb(0, 0, 0);")
        self.pushButton_3.setObjectName("pushButton_3")
        self.label_4 = QtWidgets.QLabel(self.centralwidget)
        self.label_4.setGeometry(QtCore.QRect(640, 210, 141, 51))
        font = QtGui.QFont()
        font.setFamily("微软雅黑")
        font.setPointSize(12)
        self.label_4.setFont(font)
        self.label_4.setStyleSheet("color: rgb(0, 0, 0);")
        self.label_4.setObjectName("label_4")
        self.textEdit_4 = QtWidgets.QTextEdit(self.centralwidget)
        self.textEdit_4.setEnabled(False)
        self.textEdit_4.setGeometry(QtCore.QRect(640, 260, 281, 31))
        self.textEdit_4.setStyleSheet("\n"
"background-color: rgb(255, 255, 255);")
        self.textEdit_4.setObjectName("textEdit_4")
        self.label_2.raise_()
        self.label_3.raise_()
        self.pushButton.raise_()
        self.graphicsView.raise_()
        self.label.raise_()
        self.pushButton_2.raise_()
        self.textEdit.raise_()
        self.textEdit_2.raise_()
        self.textEdit_3.raise_()
        self.pushButton_3.raise_()
        self.label_4.raise_()
        self.textEdit_4.raise_()
        # self.lb.raise_()
        mainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(mainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 958, 26))
        self.menubar.setObjectName("menubar")
        mainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(mainWindow)
        self.statusbar.setObjectName("statusbar")
        mainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(mainWindow)
        QtCore.QMetaObject.connectSlotsByName(mainWindow)
        self.pushButton.clicked.connect(self.on)
        self.pushButton_2.clicked.connect(self.pb_2)
        self.pushButton_3.clicked.connect(QCoreApplication.instance().quit)


    def retranslateUi(self, mainWindow):
        _translate = QtCore.QCoreApplication.translate
        mainWindow.setWindowTitle(_translate("mainWindow", "舌像裂纹分析"))
        self.label.setText(_translate("mainWindow", "裂纹条数:"))
        self.label_2.setText(_translate("mainWindow", "裂纹所占像素点个数:"))
        self.label_3.setText(_translate("mainWindow", "裂纹占整个舌头的比例:"))
        self.pushButton.setText(_translate("mainWindow", "Next"))
        self.pushButton_2.setText(_translate("mainWindow", "选择文件夹"))
        self.pushButton_3.setText(_translate("mainWindow", "保存并退出"))
        self.label_4.setText(_translate("mainWindow", "当前图片名称："))

    def shows(self, img2):
        # img2 = img.copy()

        img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2RGB)

        height = img2.shape[0]

        width = img2.shape[1]

        ratio = float(height / width)
        new_height = 538
        new_width = 598
        withStep=new_width*3
        img = cv2.resize(img2, (new_width, new_height))
        frame = QImage(img, new_width, new_height,withStep, QImage.Format_RGB888)
        pix = QPixmap.fromImage(frame)
        self.item = QGraphicsPixmapItem(pix)
        self.scene = QGraphicsScene()  # 创建场景
        self.scene.addItem(self.item)
        self.graphicsView.setScene(self.scene)
        # cut_img = img[x0:abs(x1 - x0), y0:abs(y1 - y0)]
        #         # detection(cut_img)
        # cv2.setMouseCallback('graphicsView',on_mouse())


    def on(self):
        self.flag = True
        print("线程开启")
        self.i=self.i+1
        self.file = self.imgfiles[self.i]
        t = threading.Thread(target=self.pb_1(), name='t')
        t.start()


    def pb_2(self):
        self.i=-1
        self.openfile_name = QFileDialog.getExistingDirectory(self, '选择文件', '')
        self.imgfiles = os.listdir(self.openfile_name)
        global c, r, s1,img,x0,x1,y0,y1
        self.wb = xlwt.Workbook()
        self.ws1 = self.wb.add_sheet('A Test Sheet', cell_overwrite_ok=True)
        self.row = 1
        self.col = 1
        self.ws1.write(0, 0, "图片编号 ")
        self.wb.save('Data.xls')
        self.ws1.write(0, 1, "裂纹条数 ")
        self.wb.save('Data.xls')
        self.ws1.write(0, 2, "裂纹像素点总和 ")
        self.wb.save('Data.xls')
        self.ws1.write(0, 3, "裂纹在整个舌头中的占比 ")
        self.wb.save('Data.xls')


    def pb_1(self):
        global c, r, s1, img, x0, x1, y0, y1
        while self.flag:
            c = 0
            r = 0
            s1 = 0
            # self.textEdit_4.setText(self.file)
            # self.textEdit_3.setText("{}".format(s1))
            # self.textEdit_2.setText("{}".format(c))
            # self.textEdit.setText("{}".format(r))
            cv2.waitKey(0)
            img = cv2.imread(self.openfile_name + "/" + self.file)

            print(self.openfile_name + "/" + self.file)
            mainMindow.shows(img)
            cv2.namedWindow('image', 0)
            cv2.imshow("image", img)
            cv2.setMouseCallback('image',on_mouse)
            # cut_img = img[x0:abs(x1 - x0), y0:abs(y1 - y0)]
            # detection(cut_img)
            # cv2.waitKey(0)
            self.col = 0
            # self.textEdit_4.setText(self.file)
            # self.textEdit_3.setText("{}".format(s1))
            # self.textEdit_2.setText("{}".format(c))
            # self.textEdit.setText("{}".format(r))
            cv2.waitKey(0)
            cv2.destroyWindow('image')
            self.ws1.write(self.row, self.col, self.file)
            self.wb.save('Data.xls')
            self.col = self.col + 1
            self.ws1.write(self.row, self.col, r)
            self.wb.save('Data.xls')
            col = self.col + 1
            self.ws1.write(self.row, col, c)
            self.wb.save('Data.xls')
            col = col + 1
            self.ws1.write(self.row, col, s1)
            self.wb.save('Data.xls')
            self.row = self.row + 1
            self.flag=False
            # if self.pushButton_3.clicked():
            #     break
        self.wb.save('Data.xls')



if __name__ == "__main__":
    app = QApplication(sys.argv)
    mainMindow = Ui_mainWindow()
    mainMindow.setupUi(mainMindow)
    mainMindow.retranslateUi(mainMindow)
    mainMindow.show()

    sys.exit(app.exec_())