示例#1
0
class MainWidget(QWidget):

    # Define virtual panel coordinates for different shapes/regions
    VPCoord_Start = [316, 332]  #LeftTopX, Y
    VPCoord_Circle = [316, 332, 336, 363]  #LeftTopX, Y, RightBotX, Y
    VPCoord_Rect = [336, 332, 356, 363]  #LeftTopX, Y, RightBotX, Y
    VPCoord_Tri = [316, 363, 336, 395]  #LeftTopX, Y, RightBotX, Y
    VPCoord_Line = [336, 363, 356, 395]  #LeftTopX, Y, RightBotX, Y

    # A flag to check if the user is currently using the virtual panel
    usingVP = False

    def __init__(self, Parent=None):
        '''
                Constructor
        '''
        super().__init__(Parent)

        #The NeoSmartpen custom paper is 88.3 x 114.2 in raw coordinates
        rawLimitX = 88
        rawLimitY = 114
        multiplier = 4

        paintSizeX = rawLimitX * multiplier
        paintSizeY = rawLimitY * multiplier
        mainSizeX = paintSizeX + 30
        mainSizeY = paintSizeY + 170

        self.__InitData(
            paintSizeX,
            paintSizeY)  #First initialize data, then initialize view/interface
        self.__InitView(mainSizeX, mainSizeY)
        self.__InitWiFi()

    def __InitWiFi(self):
        '''
                  initialize the tcp server
        '''
        self.WiFiThread = WiFiThread()
        self.WiFiThread.sigOut.connect(self.free_draw_updates)
        # self.WiFiThread.sigOut.connect(self.VP_draw_updates)
        self.WiFiThread.start()

    def __InitData(self, sizeX, sizeY):
        '''
                  initialize data
        '''
        self.__paintBoard = PaintBoard(sizeX, sizeY)
        self.__colorList = QColor.colorNames()  #Get a list of color names
        self.penCoordinates = [0, 0]
        self.penPressure = 0

    def __InitView(self, sizeX, sizeY):
        '''
                  initialize UI
        '''
        print("inside MainWidget")
        self.setFixedSize(sizeX, sizeY)
        self.setWindowTitle("PaintBoard Example PyQt5")

        main_layout = QVBoxLayout(
            self)  #Create a new horizontal box layout as the main UI
        main_layout.setSpacing(
            10)  #Set the inner border space and space between wedgets to 10px

        self.sub_layout_root = QHBoxLayout(
        )  # Create a sub layuout to place button on top
        self.sub_layout_control = QGridLayout(
        )  # Create a new horizontal sub layout for control buttons
        self.sub_layout_CAD = QGridLayout(
        )  # Create a new grid sub layout for CAD buttons

        self.sub_layout_root.setSpacing(20)
        self.sub_layout_control.setSpacing(5)
        self.sub_layout_CAD.setSpacing(5)
        self.sub_layout_root.setContentsMargins(0, 0, 10, 0)

        self.__init_control_buttons()
        self.__init_CAD_buttons()

        Separator = QFrame()
        Separator.setFrameShape(QFrame.VLine)
        Separator.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Expanding)
        Separator.setLineWidth(1)

        self.sub_layout_root.addLayout(self.sub_layout_CAD, 2)
        self.sub_layout_root.addWidget(Separator)
        self.sub_layout_root.addLayout(self.sub_layout_control, 2)

        main_layout.addLayout(
            self.sub_layout_root)  #Add the sub-layout to the main UI
        main_layout.addWidget(
            self.__paintBoard
        )  #put the paintboard at the left side of the main UI

    # Initialize buttons for control functionalities
    def __init_control_buttons(self):
        self.__btn_Clear = QPushButton("Clear")
        self.__btn_Clear.setParent(self)  #set the parent to self (the main UI)
        self.__btn_Clear.clicked.connect(
            self.__paintBoard.Clear
        )  #connect the "clear" button to the "clear paintboard" method
        self.sub_layout_control.addWidget(self.__btn_Clear, 0, 0)

        self.__btn_Quit = QPushButton("Quit")
        self.__btn_Quit.setParent(self)  #set the parent to self (the main UI)
        self.__btn_Quit.clicked.connect(self.Quit)
        self.sub_layout_control.addWidget(self.__btn_Quit, 0, 1)

        self.__btn_Save = QPushButton("Save")
        self.__btn_Save.setParent(self)
        self.__btn_Save.clicked.connect(self.on_btn_Save_Clicked)
        self.sub_layout_control.addWidget(self.__btn_Save, 1, 0)

        self.__cbtn_Eraser = QCheckBox("Eraser")
        self.__cbtn_Eraser.setParent(self)
        self.__cbtn_Eraser.clicked.connect(self.on_cbtn_Eraser_clicked)
        self.sub_layout_control.addWidget(self.__cbtn_Eraser, 1, 1)

        splitter = QSplitter(self)  #a splitter to add space
        self.sub_layout_control.addWidget(splitter)

        self.__label_penThickness = QLabel(self)
        self.__label_penThickness.setText("Thickness")
        self.__label_penThickness.setFixedHeight(20)
        self.sub_layout_control.addWidget(self.__label_penThickness, 2, 0)

        self.__spinBox_penThickness = QSpinBox(self)
        self.__spinBox_penThickness.setMaximum(10)
        self.__spinBox_penThickness.setMinimum(1)
        self.__spinBox_penThickness.setValue(2)  #default thickness is 2
        self.__spinBox_penThickness.setSingleStep(1)  #minimum single step is 1
        self.__spinBox_penThickness.valueChanged.connect(
            self.on_PenThicknessChange
        )  #Connect spinBox's value change to on_PenThicknessChange method
        self.sub_layout_control.addWidget(self.__spinBox_penThickness, 2, 1)

        self.__label_penColor = QLabel(self)
        self.__label_penColor.setText("Color")
        self.__label_penColor.setFixedHeight(20)
        self.sub_layout_control.addWidget(self.__label_penColor, 3, 0)

        self.__comboBox_penColor = QComboBox(self)
        self.__fillColorList(self.__comboBox_penColor
                             )  #Fill the color table/list with various colors
        self.__comboBox_penColor.currentIndexChanged.connect(
            self.on_PenColorChange)  #Connect to function on_PenColorChange
        self.sub_layout_control.addWidget(self.__comboBox_penColor, 3, 1)

    # Initialize buttons for CAD functionalities
    def __init_CAD_buttons(self):
        self.__cbtn_DrawCircle = QPushButton("Circle")
        self.__cbtn_DrawCircle.setParent(self)
        self.__cbtn_DrawCircle.clicked.connect(self.on_cbtn_DrawCircle_clicked)
        self.sub_layout_CAD.addWidget(self.__cbtn_DrawCircle, 1, 0)

        self.__cbtn_DrawRect = QPushButton("Rectangle")
        self.__cbtn_DrawRect.setParent(self)
        self.__cbtn_DrawRect.clicked.connect(self.on_cbtn_DrawRect_clicked)
        self.sub_layout_CAD.addWidget(self.__cbtn_DrawRect, 1, 1)

        self.__cbtn_DrawTriangle = QPushButton("Triangle")
        self.__cbtn_DrawTriangle.setParent(self)
        self.__cbtn_DrawTriangle.clicked.connect(
            self.on_cbtn_DrawTriangle_clicked)
        self.sub_layout_CAD.addWidget(self.__cbtn_DrawTriangle, 2, 0)

        self.__cbtn_DrawTriangle = QPushButton("Arc")
        self.__cbtn_DrawTriangle.setParent(self)
        self.__cbtn_DrawTriangle.clicked.connect(
            self.on_cbtn_DrawTriangle_clicked)
        self.sub_layout_CAD.addWidget(self.__cbtn_DrawTriangle, 2, 1)

        self.__cbtn_DrawLine = QPushButton("Line")
        self.__cbtn_DrawLine.setParent(self)
        self.__cbtn_DrawLine.clicked.connect(self.on_cbtn_DrawLine_clicked)
        self.sub_layout_CAD.addWidget(self.__cbtn_DrawLine, 3, 0)

        self.__cbtn_DrawTriangle = QPushButton("Spline")
        self.__cbtn_DrawTriangle.setParent(self)
        self.__cbtn_DrawTriangle.clicked.connect(
            self.on_cbtn_DrawTriangle_clicked)
        self.sub_layout_CAD.addWidget(self.__cbtn_DrawTriangle, 3, 1)

    def __fillColorList(self, comboBox):

        index_black = 0
        index = 0
        for color in self.__colorList:
            if color == "black":
                index_black = index
            index += 1
            pix = QPixmap(70, 20)
            pix.fill(QColor(color))
            comboBox.addItem(QIcon(pix), None)
            comboBox.setIconSize(QSize(70, 20))
            comboBox.setSizeAdjustPolicy(QComboBox.AdjustToContents)

        comboBox.setCurrentIndex(index_black)

    def on_PenColorChange(self):
        color_index = self.__comboBox_penColor.currentIndex()
        color_str = self.__colorList[color_index]
        self.__paintBoard.ChangePenColor(color_str)

    def on_PenThicknessChange(self):
        penThickness = self.__spinBox_penThickness.value()
        self.__paintBoard.ChangePenThickness(penThickness)

    def on_btn_Save_Clicked(self):
        savePath = QFileDialog.getSaveFileName(self, 'Save Your Paint', '.\\',
                                               '*.png')
        print(savePath)
        if savePath[0] == "":
            print("Save cancel")
            return
        image = self.__paintBoard.GetContentAsQImage()
        image.save(savePath[0])

    def on_cbtn_Eraser_clicked(self):
        if self.__cbtn_Eraser.isChecked():
            self.__paintBoard.EraserMode = True  #Enter Eraser Mode [Note: The eraser mode does not work yet]
        else:
            self.__paintBoard.EraserMode = False  #Quit Eraser Mode

    # CAD functionalities
    def on_cbtn_DrawCircle_clicked(self):
        painter = QPainter(self)
        window = Dialog(['center', 'radias'])
        data = window.getData(['center', 'radias'])
        self.usingVP = False
        center_x = int(data[0].split(',')[0])
        center_y = int(data[0].split(',')[1])
        radias = int(data[1])
        self.__paintBoard.paintEllipse(center_x, center_y, radias, radias)

    def on_cbtn_DrawRect_clicked(self):
        painter = QPainter(self)
        window = Dialog(['center', 'upper left point'])
        data = window.getData(['center', 'upper left point'])
        self.usingVP = False
        center_x = int(data[0].split(',')[0])
        center_y = int(data[0].split(',')[1])
        upper_left_x = int(data[1].split(',')[0])
        upper_left_y = int(data[1].split(',')[1])
        self.__paintBoard.paintRect(center_x, center_y, upper_left_x,
                                    upper_left_y)

    def on_cbtn_DrawTriangle_clicked(self):
        painter = QPainter(self)
        window = Dialog(['point1', 'point2', 'point3'])
        data = window.getData(['point1', 'point2', 'point3'])
        self.usingVP = False
        P1_x = int(data[0].split(',')[0])
        P1_y = int(data[0].split(',')[1])
        P2_x = int(data[1].split(',')[0])
        P2_y = int(data[1].split(',')[1])
        P3_x = int(data[2].split(',')[0])
        P3_y = int(data[2].split(',')[1])
        points = QPolygon(
            [QPoint(P1_x, P1_y),
             QPoint(P2_x, P2_y),
             QPoint(P3_x, P3_y)])
        self.__paintBoard.paintTriangle(points)

    def on_cbtn_DrawLine_clicked(self):
        painter = QPainter(self)
        window = Dialog(['Point1', 'Point2'])
        data = window.getData(['Point1', 'Point2'])
        self.usingVP = False
        P1_x = int(data[0].split(',')[0])
        P1_y = int(data[0].split(',')[1])
        P2_x = int(data[1].split(',')[0])
        P2_y = int(data[1].split(',')[1])
        self.__paintBoard.paintLine(P1_x, P1_y, P2_x, P2_y)

    '''
    def on_cbtn_DrawArc_clicked(self):
        painter = QPainter(self)
        window = Dialog(['center', 'upper left point'])
        data = window.getData(['center', 'upper left point'])
        center_x = int(data[0].split(',')[0])
        center_y = int(data[0].split(',')[1])
        upper_left_x = int(data[1].split(',')[0])
        upper_left_y = int(data[1].split(',')[1])
        self.__paintBoard.paintRect(center_x, center_y, upper_left_x, upper_left_y)

    def on_cbtn_DrawSpline_clicked(self):
        painter = QPainter(self)
        window = Dialog(['center', 'upper left point'])
        data = window.getData(['center', 'upper left point'])
        center_x = int(data[0].split(',')[0])
        center_y = int(data[0].split(',')[1])
        upper_left_x = int(data[1].split(',')[0])
        upper_left_y = int(data[1].split(',')[1])
        self.__paintBoard.paintRect(center_x, center_y, upper_left_x, upper_left_y)
    '''

    # Free drawing functionalities
    def free_draw_updates(self, penDataList):
        if penDataList is not None:
            # print(penDataList)
            if (penDataList[0] < self.VPCoord_Start[0]
                    or penDataList[1] < self.VPCoord_Start[1]):
                self.penCoordinates[0] = penDataList[0]
                self.penCoordinates[1] = penDataList[1]
                self.penPressure = penDataList[2]
                self.__paintBoard.penMoveEvent(self.penCoordinates,
                                               self.penPressure)

            elif (penDataList[2] > 200 and self.usingVP is False):
                '''
                self.penCoordinates[0] = penDataList[0]
                self.penCoordinates[1] = penDataList[1]
                self.penPressure = penDataList[2]
                '''
                # print(penDataList)
                pen_x = penDataList[0]
                pen_y = penDataList[1]
                pen_pressure = penDataList[2]

                # Check which region the pen is in and prepare to draw shape accordingly
                if (pen_x < self.VPCoord_Circle[2]
                        and pen_y < self.VPCoord_Circle[3]):
                    print("Circle")
                    self.usingVP = True
                    self.on_cbtn_DrawCircle_clicked()
                elif (pen_x < self.VPCoord_Rect[2]
                      and pen_y < self.VPCoord_Rect[3]):
                    print("Rect")
                    self.usingVP = True
                    self.on_cbtn_DrawRect_clicked()
                elif (pen_x < self.VPCoord_Tri[2]
                      and pen_y < self.VPCoord_Tri[3]):
                    print("Tri")
                    self.usingVP = True
                    self.on_cbtn_DrawTriangle_clicked()
                elif (pen_x < self.VPCoord_Line[2]
                      and pen_y < self.VPCoord_Line[3]):
                    print("Line")
                    self.usingVP = True
                    self.on_cbtn_DrawLine_clicked()

                #self.__paintBoard.penVPEvent(self.penCoordinates, self.penPressure)

    def Quit(self):
        self.close()
示例#2
0
class MainWidget(QWidget):
    def __init__(self, Parent=None):
        '''
        Constructor
        '''
        super().__init__(Parent)

        self.__InitData()  #先初始化数据,再初始化界面
        self.__InitView()
        self.svmModel = model.loadModel()

    def __InitData(self):
        '''
                  初始化成员变量
        '''
        self.__paintBoard = PaintBoard(self)
        #获取颜色列表(字符串类型)
        self.__colorList = QColor.colorNames()

    def __InitView(self):
        '''
                  初始化界面
        '''
        self.setFixedSize(640, 480)
        self.setWindowTitle("PaintBoard Example PyQt5")

        #新建一个水平布局作为本窗体的主布局
        main_layout = QHBoxLayout(self)
        #设置主布局内边距以及控件间距为10px
        main_layout.setSpacing(10)

        #在主界面左侧放置画板
        main_layout.addWidget(self.__paintBoard)

        #新建垂直子布局用于放置按键
        sub_layout = QVBoxLayout()

        #设置此子布局和内部控件的间距为10px
        sub_layout.setContentsMargins(10, 10, 10, 10)

        self.__btn_Clear = QPushButton("清空画板")
        self.__btn_Clear.setParent(self)  #设置父对象为本界面
        self.__btn_Clear.clicked.connect(self.on_clear)  #将按键按下信号与画板清空函数相关联
        sub_layout.addWidget(self.__btn_Clear)

        self.__btn_Save = QPushButton("识别")
        self.__btn_Save.setParent(self)
        self.__btn_Save.clicked.connect(self.on_btn_Save_Clicked)
        sub_layout.addWidget(self.__btn_Save)

        self.__text_predict = QLineEdit(self)
        sub_layout.addWidget(self.__text_predict)

        self.__cbtn_Eraser = QCheckBox("  使用橡皮擦")
        self.__cbtn_Eraser.setParent(self)
        self.__cbtn_Eraser.clicked.connect(self.on_cbtn_Eraser_clicked)
        sub_layout.addWidget(self.__cbtn_Eraser)

        splitter = QSplitter(self)  #占位符
        sub_layout.addWidget(splitter)

        self.__btn_Quit = QPushButton("退出")
        self.__btn_Quit.setParent(self)  #设置父对象为本界面
        self.__btn_Quit.clicked.connect(self.Quit)
        sub_layout.addWidget(self.__btn_Quit)

        self.__label_penThickness = QLabel(self)
        self.__label_penThickness.setText("画笔粗细")
        self.__label_penThickness.setFixedHeight(20)
        sub_layout.addWidget(self.__label_penThickness)

        self.__spinBox_penThickness = QSpinBox(self)
        self.__spinBox_penThickness.setMaximum(20)
        self.__spinBox_penThickness.setMinimum(2)
        self.__spinBox_penThickness.setValue(10)  #默认粗细为10
        self.__spinBox_penThickness.setSingleStep(2)  #最小变化值为2
        self.__spinBox_penThickness.valueChanged.connect(
            self.on_PenThicknessChange
        )  #关联spinBox值变化信号和函数on_PenThicknessChange
        sub_layout.addWidget(self.__spinBox_penThickness)

        self.__label_penColor = QLabel(self)
        self.__label_penColor.setText("画笔颜色")
        self.__label_penColor.setFixedHeight(20)
        sub_layout.addWidget(self.__label_penColor)

        self.__comboBox_penColor = QComboBox(self)
        self.__fillColorList(self.__comboBox_penColor)  #用各种颜色填充下拉列表
        self.__comboBox_penColor.currentIndexChanged.connect(
            self.on_PenColorChange)  #关联下拉列表的当前索引变更信号与函数on_PenColorChange
        sub_layout.addWidget(self.__comboBox_penColor)

        main_layout.addLayout(sub_layout)  #将子布局加入主布局

    def __fillColorList(self, comboBox):

        index_black = 0
        index = 0
        for color in self.__colorList:
            if color == "black":
                index_black = index
            index += 1
            pix = QPixmap(70, 20)
            pix.fill(QColor(color))
            comboBox.addItem(QIcon(pix), None)
            comboBox.setIconSize(QSize(70, 20))
            comboBox.setSizeAdjustPolicy(QComboBox.AdjustToContents)

        comboBox.setCurrentIndex(index_black)

    def on_PenColorChange(self):
        color_index = self.__comboBox_penColor.currentIndex()
        color_str = self.__colorList[color_index]
        self.__paintBoard.ChangePenColor(color_str)

    def on_PenThicknessChange(self):
        penThickness = self.__spinBox_penThickness.value()
        self.__paintBoard.ChangePenThickness(penThickness)

    def on_clear(self):
        self.__paintBoard.Clear()
        self.__text_predict.setText("")

    def on_btn_Save_Clicked(self):
        image = self.__paintBoard.GetContentAsQImage()
        image.save("tmpimageforsvm.png")
        img = cv2.imread("tmpimageforsvm.png")
        img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        img = cv2.resize(img, (28, 28))
        Array = np.empty((1, 28 * 28))
        Array[0] = img.reshape((1, 28 * 28))
        ret = self.svmModel.predict(model.reNormalize(Array))
        print(ret)
        self.__text_predict.setText("预测值{}".format(int(ret)))

    def on_cbtn_Eraser_clicked(self):
        if self.__cbtn_Eraser.isChecked():
            self.__paintBoard.EraserMode = True  #进入橡皮擦模式
        else:
            self.__paintBoard.EraserMode = False  #退出橡皮擦模式

    def Quit(self):
        self.close()
示例#3
0
class MainWidget(QWidget):
    def __init__(self, Parent=None):
        '''
        Constructor
        '''
        super().__init__(Parent)

        self.__InitData()  #先初始化数据,再初始化界面
        self.__InitView()

    def __InitData(self):
        '''
                  初始化成员变量
        '''
        self.__paintBoard = PaintBoard(self)
        #获取颜色列表(字符串类型)
        self.__colorList = QColor.colorNames()

    def __InitView(self):
        '''
                  初始化界面
        '''
        self.setFixedSize(640, 480)
        self.setWindowTitle("PaintBoard Example PyQt5")

        #新建一个水平布局作为本窗体的主布局
        main_layout = QHBoxLayout(self)
        #设置主布局内边距以及控件间距为10px
        main_layout.setSpacing(10)

        #在主界面左侧放置画板
        main_layout.addWidget(self.__paintBoard)

        #新建垂直子布局用于放置按键
        sub_layout = QVBoxLayout()

        #设置此子布局和内部控件的间距为5px
        sub_layout.setContentsMargins(5, 5, 5, 5)

        splitter = QSplitter(self)  #占位符
        sub_layout.addWidget(splitter)

        self.__btn_Recognize = QPushButton("开始识别")
        self.__btn_Recognize.setParent(self)
        self.__btn_Recognize.clicked.connect(self.on_btn_Recognize_Clicked)
        sub_layout.addWidget(self.__btn_Recognize)

        self.__btn_Clear = QPushButton("清空画板")
        self.__btn_Clear.setParent(self)  #设置父对象为本界面

        #将按键按下信号与画板清空函数相关联
        self.__btn_Clear.clicked.connect(self.__paintBoard.Clear)
        sub_layout.addWidget(self.__btn_Clear)

        self.__btn_Quit = QPushButton("退出")
        self.__btn_Quit.setParent(self)  #设置父对象为本界面
        self.__btn_Quit.clicked.connect(self.Quit)
        sub_layout.addWidget(self.__btn_Quit)

        self.__btn_Save = QPushButton("保存作品")
        self.__btn_Save.setParent(self)
        self.__btn_Save.clicked.connect(self.on_btn_Save_Clicked)
        sub_layout.addWidget(self.__btn_Save)

        self.__cbtn_Eraser = QCheckBox("  使用橡皮擦")
        self.__cbtn_Eraser.setParent(self)
        self.__cbtn_Eraser.clicked.connect(self.on_cbtn_Eraser_clicked)
        sub_layout.addWidget(self.__cbtn_Eraser)

        self.__label_penThickness = QLabel(self)
        self.__label_penThickness.setText("画笔粗细")
        self.__label_penThickness.setFixedHeight(20)
        sub_layout.addWidget(self.__label_penThickness)

        self.__spinBox_penThickness = QSpinBox(self)
        self.__spinBox_penThickness.setMaximum(20)
        self.__spinBox_penThickness.setMinimum(2)
        self.__spinBox_penThickness.setValue(10)  #默认粗细为10
        self.__spinBox_penThickness.setSingleStep(2)  #最小变化值为2
        self.__spinBox_penThickness.valueChanged.connect(
            self.on_PenThicknessChange
        )  #关联spinBox值变化信号和函数on_PenThicknessChange
        sub_layout.addWidget(self.__spinBox_penThickness)

        self.__label_penColor = QLabel(self)
        self.__label_penColor.setText("画笔颜色")
        self.__label_penColor.setFixedHeight(20)
        sub_layout.addWidget(self.__label_penColor)

        self.__comboBox_penColor = QComboBox(self)
        self.__fillColorList(self.__comboBox_penColor)  #用各种颜色填充下拉列表
        self.__comboBox_penColor.currentIndexChanged.connect(
            self.on_PenColorChange)  #关联下拉列表的当前索引变更信号与函数on_PenColorChange
        sub_layout.addWidget(self.__comboBox_penColor)

        main_layout.addLayout(sub_layout)  #将子布局加入主布局

    def __fillColorList(self, comboBox):

        index_black = 0
        index = 0
        for color in self.__colorList:
            if color == "black":
                index_black = index
            index += 1
            pix = QPixmap(70, 20)
            pix.fill(QColor(color))
            comboBox.addItem(QIcon(pix), None)
            comboBox.setIconSize(QSize(70, 20))
            comboBox.setSizeAdjustPolicy(QComboBox.AdjustToContents)

        comboBox.setCurrentIndex(index_black)

    def on_PenColorChange(self):
        color_index = self.__comboBox_penColor.currentIndex()
        color_str = self.__colorList[color_index]
        self.__paintBoard.ChangePenColor(color_str)

    def on_PenThicknessChange(self):
        penThickness = self.__spinBox_penThickness.value()
        self.__paintBoard.ChangePenThickness(penThickness)

    def on_btn_Save_Clicked(self):
        savePath = QFileDialog.getSaveFileName(self, 'Save Your Paint', '.\\',
                                               '*.png')
        print(savePath)
        if savePath[0] == "":
            print("Save cancel")
            return
        image = self.__paintBoard.GetContentAsQImage()
        image.save(savePath[0])
        print(savePath[0])

    def on_cbtn_Eraser_clicked(self):
        if self.__cbtn_Eraser.isChecked():
            self.__paintBoard.EraserMode = True  #进入橡皮擦模式
        else:
            self.__paintBoard.EraserMode = False  #退出橡皮擦模式

    def on_btn_Recognize_Clicked(self):

        savePath = "text.png"
        image = self.__paintBoard.GetContentAsQImage()
        image.save(savePath)
        print(savePath)
        # 加载图像
        img = keras.preprocessing.image.load_img(savePath,
                                                 target_size=(28, 28))
        img = img.convert('L')
        x = keras.preprocessing.image.img_to_array(img)
        x = abs(255 - x)
        #x = x.reshape(28,28)
        x = np.expand_dims(x, axis=0)
        x = x / 255.0
        new_model = keras.models.load_model('my_model.h5')
        prediction = new_model.predict(x)
        output = np.argmax(prediction, axis=1)
        print("letter written:" + str(chr(output[0])))

    def Quit(self):
        self.close()
示例#4
0
class MainWidget(QWidget):
    def __init__(self, Parent=None):

        super().__init__(Parent)

        self.__InitData()
        self.__InitView()
        f = open("params15000.json", "r")
        data = json.load(f)
        f.close()
        self.biase = np.array(data["biase"])
        self.w_in = np.array(data["w_in"])
        self.w_out = np.array(data["w_out"])

    def __InitData(self):

        self.__paintBoard = PaintBoard(self)
        self.__colorList = QColor.colorNames()

    def __InitView(self):

        # self.setFixedSize(640,480)
        # self.setFixedSize(480,410)
        self.setFixedSize(800, 618)
        self.setWindowTitle("基于ELM的快速手写识别软件NeuHandWriting (NeuHWR1.0)")
        self.setWindowIcon(QIcon('ICON.ico'))

        main_layout = QHBoxLayout(self)
        main_layout.setSpacing(10)

        main_layout.addWidget(self.__paintBoard)

        self.font = QtGui.QFont()
        self.font.setFamily("Consolas")
        self.font.setPointSize(15)

        sub_layout = QVBoxLayout()
        sub_layout.setContentsMargins(10, 10, 10, 10)

        self.__btn_Clear = QPushButton("Clear Board")
        self.__btn_Clear.setParent(self)
        self.__btn_Clear.setFixedSize(146, 70)
        self.__btn_Clear.setFont(self.font)
        self.__btn_Clear.clicked.connect(self.__paintBoard.Clear)
        sub_layout.addWidget(self.__btn_Clear)

        self.__btn_Quit = QPushButton("Exit")
        self.__btn_Quit.setParent(self)
        self.__btn_Quit.setFixedSize(146, 70)
        self.__btn_Quit.setFont(self.font)
        self.__btn_Quit.clicked.connect(self.Quit)
        sub_layout.addWidget(self.__btn_Quit)

        self.__btn_Save = QPushButton("Save Board")
        self.__btn_Save.setParent(self)
        self.__btn_Save.setFixedSize(146, 70)
        self.__btn_Save.setFont(self.font)
        self.__btn_Save.clicked.connect(self.on_btn_Save_Clicked)
        sub_layout.addWidget(self.__btn_Save)

        self.__cbtn_Eraser = QCheckBox("Eraser")
        self.__cbtn_Eraser.setParent(self)
        self.__cbtn_Eraser.setFont(self.font)
        self.__cbtn_Eraser.clicked.connect(self.on_cbtn_Eraser_clicked)
        sub_layout.addWidget(self.__cbtn_Eraser)

        self.__label_result = QLabel(self)
        self.__label_result.setAlignment(Qt.AlignCenter)
        self.__label_result.setFixedWidth(146)
        self.__label_result.setFixedHeight(80)
        self.__label_result.setFrameStyle(PyQt5.QtWidgets.QFrame.Box)
        self.__label_result.setFrameShadow(PyQt5.QtWidgets.QFrame.Raised)
        self.__label_result.setLineWidth(6)
        self.__label_result.setMidLineWidth(5)
        self.__label_result.setStyleSheet('background-color: rgb(255,123,100)')
        sub_layout.addWidget(self.__label_result)

        self.__btn_Recognize = QPushButton("Recognition")
        self.__btn_Recognize.setParent(self)
        self.__btn_Recognize.setFixedSize(146, 70)
        self.__btn_Recognize.setFont(self.font)
        self.__btn_Recognize.clicked.connect(self.on_btn_Recognize_clicked)
        sub_layout.addWidget(self.__btn_Recognize)

        self.__label_timage = QLabel(self)
        self.__label_timage.setAlignment(Qt.AlignCenter)
        self.__label_timage.setFixedWidth(146)
        self.__label_timage.setFixedHeight(80)
        self.__label_timage.setFrameStyle(PyQt5.QtWidgets.QFrame.Box)
        self.__label_timage.setFrameShadow(PyQt5.QtWidgets.QFrame.Raised)
        self.__label_timage.setLineWidth(6)
        self.__label_timage.setMidLineWidth(5)
        self.__label_timage.setStyleSheet('background-color: rgb(125,143,50)')
        sub_layout.addWidget(self.__label_timage)

        self.__btn_Random = QPushButton("RandomDigit \nFrom TestSet")
        self.__btn_Random.setParent(self)
        self.__btn_Random.setFixedSize(146, 70)
        self.font.setPointSize(13)
        self.__btn_Random.setFont(self.font)
        self.__btn_Random.clicked.connect(self.on_btn_RandomDigit_Clicked)
        sub_layout.addWidget(self.__btn_Random)

        main_layout.addLayout(sub_layout)

    def __fillColorList(self, comboBox):

        index_black = 0
        index = 0
        for color in self.__colorList:
            if color == "black":
                index_black = index
            index += 1
            pix = QPixmap(70, 20)
            pix.fill(QColor(color))
            comboBox.addItem(QIcon(pix), None)
            comboBox.setIconSize(QSize(70, 20))
            comboBox.setSizeAdjustPolicy(QComboBox.AdjustToContents)

        comboBox.setCurrentIndex(index_black)

    def on_PenColorChange(self):
        color_index = self.__comboBox_penColor.currentIndex()
        color_str = self.__colorList[color_index]
        self.__paintBoard.ChangePenColor(color_str)

    def on_PenThicknessChange(self):
        penThickness = self.__spinBox_penThickness.value()
        self.__paintBoard.ChangePenThickness(penThickness)

    def on_btn_Save_Clicked(self):
        savePath = QFileDialog.getSaveFileName(self, 'Save Your Paint', '.\\',
                                               '*.png')
        print(savePath)
        if savePath[0] == "":
            print("Save cancel")
            return
        image = self.__paintBoard.GetContentAsQImage()
        image.save(savePath[0])

    def on_cbtn_Eraser_clicked(self):
        if self.__cbtn_Eraser.isChecked():
            self.__paintBoard.EraserMode = True
        else:
            self.__paintBoard.EraserMode = False

    def on_btn_RandomDigit_Clicked(self):
        f = open('x_test_10000.pkl', 'rb')
        x_test = pickle.load(f, encoding='bytes')
        f.close()
        ff = open('y_test_10000.pkl', 'rb')
        y_test = pickle.load(ff, encoding='bytes')
        ff.close()
        random_id = random.randint(0, 9999)
        image = Image.fromarray(np.reshape(x_test[random_id],
                                           (28, 28)) * 255).convert('L')
        new_image = image.resize((44, 44))
        # new_image.show()
        new_image.save('tpic.png')
        pixmap = QPixmap('tpic.png')
        self.__label_timage.setPixmap(pixmap)
        print("begin")
        res = self.judge(np.reshape(x_test[random_id], (28, 28)))
        myres = "{0}|{1}".format(res, int(y_test[random_id]))

        # show my result
        font = QtGui.QFont()
        font.setFamily('Consolas')
        font.setBold(True)
        font.setPointSize(18)
        font.setWeight(75)
        self.__label_result.setFont(font)
        self.__label_result.setText(myres)

    def sigmoid(self, x):
        return 1.0 / (1.0 + np.exp(-x))

    def judge(self, input_v):
        fd = hog(input_v,
                 orientations=5,
                 pixels_per_cell=(4, 4),
                 cells_per_block=(3, 3),
                 block_norm='L1-sqrt',
                 transform_sqrt=True,
                 feature_vector=True,
                 visualise=False)
        length = len(fd)
        y_hat = np.dot(
            self.w_out,
            self.sigmoid(
                np.dot(self.w_in, np.reshape(fd, (length, 1))) +
                self.biase.transpose()))
        res_id = np.argmax(y_hat)
        y_hat[y_hat < 0] = 0
        prapability = y_hat[res_id] / np.sum(y_hat)
        myres = "{0}({1}%)".format(res_id, int(prapability * 100))
        print(myres)
        return myres

    def on_btn_Recognize_clicked(self):

        savePath = "tmp.png"
        image = self.__paintBoard.GetContentAsQImage()
        image.save(savePath)

        t_image = Image.open(savePath).convert('L')
        newt_image = t_image.resize((28, 28))
        # newt_image.save("tmp1.png")
        np_image = np.array(newt_image) / 255.0
        # print (np_image.shape)
        # print (np_image)

        myres = self.judge(np_image)

        # show my result
        font = QtGui.QFont()
        font.setFamily('Consolas')
        font.setBold(True)
        font.setPointSize(20)
        font.setWeight(75)
        self.__label_result.setFont(font)
        self.__label_result.setText(myres)
        # print (myres)

    def Quit(self):
        self.close()
示例#5
0
文件: MainWidget.py 项目: Suqi2017/-
class MainWidget(QWidget):


    def __init__(self, Parent=None):
        '''
        Constructor
        '''
        super().__init__(Parent)
        
        self.__InitData() #先初始化数据,再初始化界面
        self.__InitView()
    
    def __InitData(self):
        '''
                  初始化成员变量
        '''
        self.__paintBoard = PaintBoard(self)
        #获取颜色列表(字符串类型)
        self.__colorList = QColor.colorNames() 
        
    def __InitView(self):
        '''
                  初始化界面
        '''
        self.setFixedSize(640,480)
        self.setWindowTitle("书写画板")
        
        #新建一个水平布局作为本窗体的主布局
        main_layout = QHBoxLayout(self) 
        #设置主布局内边距以及控件间距为10px
        main_layout.setSpacing(10) 
    
        #在主界面左侧放置画板
        main_layout.addWidget(self.__paintBoard) 
        
        #新建垂直子布局用于放置按键
        sub_layout = QVBoxLayout() 
        
        #设置此子布局和内部控件的间距为10px
        sub_layout.setContentsMargins(10, 10, 10, 10) 

        self.__btn_Clear = QPushButton("清空画板")
        self.__btn_Clear.setParent(self) #设置父对象为本界面
       
        #将按键按下信号与画板清空函数相关联
        self.__btn_Clear.clicked.connect(self.__paintBoard.Clear) 
        sub_layout.addWidget(self.__btn_Clear)
        
        self.__btn_Quit = QPushButton("退出")
        self.__btn_Quit.setParent(self) #设置父对象为本界面
        self.__btn_Quit.clicked.connect(self.Quit)
        sub_layout.addWidget(self.__btn_Quit)
        
        self.__btn_Save = QPushButton("预测")
        self.__btn_Save.setParent(self)
        self.__btn_Save.clicked.connect(self.on_btn_Save_Clicked)
        sub_layout.addWidget(self.__btn_Save)
        
        self.__cbtn_Eraser = QCheckBox("  使用橡皮擦")
        self.__cbtn_Eraser.setParent(self)
        self.__cbtn_Eraser.clicked.connect(self.on_cbtn_Eraser_clicked)
        sub_layout.addWidget(self.__cbtn_Eraser)
        
        splitter = QSplitter(self) #占位符
        sub_layout.addWidget(splitter)
        
        self.__label_penThickness = QLabel(self)
        self.__label_penThickness.setText("画笔粗细")
        self.__label_penThickness.setFixedHeight(20)
        sub_layout.addWidget(self.__label_penThickness)
        
        self.__spinBox_penThickness = QSpinBox(self)
        self.__spinBox_penThickness.setMaximum(20)
        self.__spinBox_penThickness.setMinimum(2)
        self.__spinBox_penThickness.setValue(10) #默认粗细为10
        self.__spinBox_penThickness.setSingleStep(2) #最小变化值为2
        self.__spinBox_penThickness.valueChanged.connect(self.on_PenThicknessChange)#关联spinBox值变化信号和函数on_PenThicknessChange
        sub_layout.addWidget(self.__spinBox_penThickness)
        
        self.__label_penColor = QLabel(self)
        self.__label_penColor.setText("画笔颜色")
        self.__label_penColor.setFixedHeight(20)
        sub_layout.addWidget(self.__label_penColor)
        
        self.__comboBox_penColor = QComboBox(self)
        self.__fillColorList(self.__comboBox_penColor) #用各种颜色填充下拉列表
        self.__comboBox_penColor.currentIndexChanged.connect(self.on_PenColorChange) #关联下拉列表的当前索引变更信号与函数on_PenColorChange
        sub_layout.addWidget(self.__comboBox_penColor)

        main_layout.addLayout(sub_layout) #将子布局加入主布局


    def __fillColorList(self, comboBox):

        index_black = 0
        index = 0
        for color in self.__colorList: 
            if color == "black":
                index_black = index
            index += 1
            pix = QPixmap(70,20)
            pix.fill(QColor(color))
            comboBox.addItem(QIcon(pix),None)
            comboBox.setIconSize(QSize(70,20))
            comboBox.setSizeAdjustPolicy(QComboBox.AdjustToContents)

        comboBox.setCurrentIndex(index_black)
        
    def on_PenColorChange(self):
        color_index = self.__comboBox_penColor.currentIndex()
        color_str = self.__colorList[color_index]
        self.__paintBoard.ChangePenColor(color_str)

    def on_PenThicknessChange(self):
        penThickness = self.__spinBox_penThickness.value()
        self.__paintBoard.ChangePenThickness(penThickness)
    
    def on_btn_Save_Clicked(self):
        '''
        savePath = QFileDialog.getSaveFileName(self, 'Save Your Paint', '.\\', '*.png')
        print(savePath)
        if savePath[0] == "":
            print("Save cancel")
            return
        '''
        image = self.__paintBoard.GetContentAsQImage()

        image.save('./img.png')
        pre('./img.png')
    def on_cbtn_Eraser_clicked(self):
        if self.__cbtn_Eraser.isChecked():
            self.__paintBoard.EraserMode = True #进入橡皮擦模式
        else:
            self.__paintBoard.EraserMode = False #退出橡皮擦模式
        
        
    def Quit(self):
        self.close()
示例#6
0
class MainWidget(QWidget):
    # 80 * 200 pallet
    # Define virtual panel coordinates for different shapes/regions
    VPCoord_Start = [80, 200]  #LeftTopX, Y (originally 316, 332)
    VPCoord_Circle = [0, 0, 40, 50]  #LeftTopX, Y, RightBotX, Y
    VPCoord_Rect = [40, 0, 80, 50]
    VPCoord_Tri = [0, 50, 40, 100]
    VPCoord_Line = [40, 50, 80, 100]
    VPCoord_Arc = [0, 100, 40, 150]
    VPCoord_Curve = [40, 100, 80, 150]
    VPCoord_Perspect = [0, 150, 40, 200]
    VPCoord_Ruler = [40, 150, 80, 200]
    # VPCoord_Copy    =   [0,  150, 40, 200]
    #VPCoord_Paste   =   [40, 150, 80, 200]

    # A flag to check if the user is currently using the virtual panel
    usingVP = False
    usingVP_Line = False
    usingVP_Rect = False
    usingVP_Circle = False
    usingVP_Arc = False
    usingVP_Tri = False
    usingVP_Curve = False
    usingVP_Copy = False
    usingVP_Paste = False
    usingVP_Perspect = False
    usingVP_VPoint = False
    usingVP_Ruler = False

    # a flag to check if the user is using the motor to draw shapes
    usingMotor = False
    usingMotor_Line = False

    vpPointCount = 0
    vpShapePointList = []
    vpCopyPointList = []
    vpVanishingPoint = []
    vpVpoint = []

    controlLineSignal = pyqtSignal(list)
    controlRectSignal = pyqtSignal(list)
    controlRectPSignal = pyqtSignal(list)
    controlTriSignal = pyqtSignal(list)
    gcoordinate = pyqtSignal(list)

    # A deque used to store the recent "lifted" variable from the pen due to asynch bluetooth transmission
    liftedDeque = collections.deque(3 * [True], 3)

    # Lists for circle's radius and coordinates
    list_circle_r = [0]
    list_circle_x = [0]
    list_circle_y = [0]

    def __init__(self, Parent=None):
        '''
                Constructor
        '''
        super(MainWidget, self).__init__(Parent)

        #The NeoSmartpen custom paper is 88.3 x 114.2 in raw coordinates
        rawLimitX = 88
        rawLimitY = 114
        multiplier = 8

        paintSizeX = rawLimitX * multiplier
        paintSizeY = rawLimitY * multiplier
        mainSizeX = paintSizeX + 30
        mainSizeY = paintSizeY + 170

        self.__InitData(
            paintSizeX,
            paintSizeY)  #First initialize data, then initialize view/interface
        self.__InitView(mainSizeX, mainSizeY)
        #self.__InitWiFi()
        self.__InitBluetooth()
        #self.__InitControl()

    '''
    def __InitWiFi(self):
        
                  #initialize the tcp server
        
        self.WiFiThread = WiFiThread()
        self.WiFiThread.sigOut.connect(self.free_draw_updates)
        # self.WiFiThread.sigOut.connect(self.VP_draw_updates)
        self.WiFiThread.start()
    '''

    def __InitBluetooth(self):
        '''
                 initialize the bluetooth
        '''
        self.BluetoothThread = BluetoothThread()
        self.BluetoothThread.sigOut.connect(self.free_draw_updates)
        # self.WiFiThread.sigOut.connect(self.VP_draw_updates)
        self.BluetoothThread.start()

    """
    def __InitControl(self):
        '''
                 initialize the motor control
        '''
        self.ControlThread = ControlThread()
        self.controlLineSignal.connect(self.ControlThread.receiveLineData)
        self.controlRectSignal.connect(self.ControlThread.receiveRectData)
        self.controlRectPSignal.connect(self.ControlThread.receiveRectPData)
        self.controlTriSignal.connect(self.ControlThread.receiveTriData)
        self.gcoordinate.connect(self.ControlThread.gpos)
        self.ControlThread.start()
    """

    def __InitData(self, sizeX, sizeY):
        '''
                  initialize data
        '''
        self.__paintBoard = PaintBoard(sizeX, sizeY)
        self.__colorList = QColor.colorNames()  #Get a list of color names
        self.penCoordinates = [0, 0]
        self.penPressure = 0

    def __InitView(self, sizeX, sizeY):
        '''
                  initialize UI
        '''
        print("inside MainWidget")
        self.setFixedSize(sizeX, sizeY)
        self.setWindowTitle("PaintBoard Example PyQt5")

        main_layout = QVBoxLayout(
            self)  #Create a new horizontal box layout as the main UI
        main_layout.setSpacing(
            10)  #Set the inner border space and space between wedgets to 10px

        self.sub_layout_root = QHBoxLayout(
        )  # Create a sub layuout to place button on top
        self.sub_layout_control = QGridLayout(
        )  # Create a new horizontal sub layout for control buttons
        self.sub_layout_CAD = QGridLayout(
        )  # Create a new grid sub layout for CAD buttons

        self.sub_layout_root.setSpacing(20)
        self.sub_layout_control.setSpacing(10)
        self.sub_layout_CAD.setSpacing(20)
        self.sub_layout_root.setContentsMargins(
            0, 0, 10, 0)  # Only set the rigt margin (10) for now

        self.__init_control_buttons()
        self.__init_CAD_buttons()

        Separator = QFrame()
        Separator.setFrameShape(QFrame.VLine)
        Separator.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Expanding)
        Separator.setLineWidth(1)

        self.sub_layout_root.addLayout(self.sub_layout_CAD, 2)
        self.sub_layout_root.addWidget(Separator)
        self.sub_layout_root.addLayout(self.sub_layout_control, 2)

        main_layout.addLayout(
            self.sub_layout_root)  #Add the sub-layout to the main UI
        main_layout.addWidget(
            self.__paintBoard
        )  #put the paintboard at the left side of the main UI

    # Initialize buttons for control functionalities
    def __init_control_buttons(self):
        self.__btn_Clear = QPushButton("Clear")
        self.__btn_Clear.setParent(self)  #set the parent to self (the main UI)
        self.__btn_Clear.clicked.connect(
            self.__paintBoard.Clear
        )  #connect the "clear" button to the "clear paintboard" method
        self.sub_layout_control.addWidget(self.__btn_Clear, 0, 0)

        self.__btn_Quit = QPushButton("Quit")
        self.__btn_Quit.setParent(self)  #set the parent to self (the main UI)
        self.__btn_Quit.clicked.connect(self.Quit)
        self.sub_layout_control.addWidget(self.__btn_Quit, 0, 1)

        self.__btn_Save = QPushButton("Save")
        self.__btn_Save.setParent(self)
        self.__btn_Save.clicked.connect(self.on_btn_Save_Clicked)
        self.sub_layout_control.addWidget(self.__btn_Save, 1, 0)

        self.__cbtn_Eraser = QCheckBox("Eraser")
        self.__cbtn_Eraser.setParent(self)
        self.__cbtn_Eraser.clicked.connect(self.on_cbtn_Eraser_clicked)
        self.sub_layout_control.addWidget(self.__cbtn_Eraser, 1, 1)

        splitter = QSplitter(self)  #a splitter to add space
        self.sub_layout_control.addWidget(splitter)

        self.__label_penThickness = QLabel(self)
        self.__label_penThickness.setText("Thickness")
        self.__label_penThickness.setFixedHeight(20)
        self.sub_layout_control.addWidget(self.__label_penThickness, 2, 0)

        self.__spinBox_penThickness = QSpinBox(self)
        self.__spinBox_penThickness.setMaximum(10)
        self.__spinBox_penThickness.setMinimum(1)
        self.__spinBox_penThickness.setValue(2)  #default thickness is 2
        self.__spinBox_penThickness.setSingleStep(1)  #minimum single step is 1
        self.__spinBox_penThickness.valueChanged.connect(
            self.on_PenThicknessChange
        )  #Connect spinBox's value change to on_PenThicknessChange method
        self.sub_layout_control.addWidget(self.__spinBox_penThickness, 2, 1)

        self.__label_penColor = QLabel(self)
        self.__label_penColor.setText("Color")
        self.__label_penColor.setFixedHeight(20)
        self.sub_layout_control.addWidget(self.__label_penColor, 3, 0)

        self.__comboBox_penColor = QComboBox(self)
        self.__fillColorList(self.__comboBox_penColor
                             )  #Fill the color table/list with various colors
        self.__comboBox_penColor.currentIndexChanged.connect(
            self.on_PenColorChange)  #on_PenColorChange
        self.sub_layout_control.addWidget(self.__comboBox_penColor, 3, 1)

    # Initialize buttons for CAD functionalities
    def __init_CAD_buttons(self):
        self.__cbtn_DrawCircle = QPushButton("")
        self.__cbtn_DrawCircle.setParent(self)
        self.__cbtn_DrawCircle.setIcon(QtGui.QIcon('icons/ellipse.png'))
        self.__cbtn_DrawCircle.clicked.connect(self.on_cbtn_DrawCircle_clicked)
        self.sub_layout_CAD.addWidget(self.__cbtn_DrawCircle, 1, 0)

        self.__cbtn_DrawRect = QPushButton("")
        self.__cbtn_DrawRect.setParent(self)
        self.__cbtn_DrawRect.setIcon(QtGui.QIcon('icons/rectangle.png'))
        self.__cbtn_DrawRect.clicked.connect(self.on_cbtn_DrawRect_clicked)
        self.sub_layout_CAD.addWidget(self.__cbtn_DrawRect, 1, 1)

        self.__cbtn_DrawTriangle = QPushButton("")
        self.__cbtn_DrawTriangle.setParent(self)
        self.__cbtn_DrawTriangle.setIcon(QtGui.QIcon('icons/polygon.png'))
        self.__cbtn_DrawTriangle.clicked.connect(
            self.on_cbtn_DrawTriangle_clicked)
        self.sub_layout_CAD.addWidget(self.__cbtn_DrawTriangle, 2, 0)

        self.__cbtn_DrawLine = QPushButton("")
        self.__cbtn_DrawLine.setParent(self)
        self.__cbtn_DrawLine.setIcon(QtGui.QIcon('icons/segment.png'))
        self.__cbtn_DrawLine.clicked.connect(self.on_cbtn_DrawLine_clicked)
        self.sub_layout_CAD.addWidget(self.__cbtn_DrawLine, 2, 1)

        self.__cbtn_DrawArc = QPushButton("")
        self.__cbtn_DrawArc.setParent(self)
        self.__cbtn_DrawArc.setIcon(QtGui.QIcon('icons/arc.png'))
        self.__cbtn_DrawArc.clicked.connect(self.on_cbtn_DrawArc_clicked)
        self.sub_layout_CAD.addWidget(self.__cbtn_DrawArc, 3, 0)

        self.__cbtn_DrawBezierSpline = QPushButton("")
        self.__cbtn_DrawBezierSpline.setParent(self)
        self.__cbtn_DrawBezierSpline.setIcon(QtGui.QIcon('icons/nurbs.png'))
        self.__cbtn_DrawBezierSpline.clicked.connect(
            self.on_cbtn_DrawBezierSpline_clicked)
        self.sub_layout_CAD.addWidget(self.__cbtn_DrawBezierSpline, 3, 1)

    def __fillColorList(self, comboBox):

        index_black = 0
        index = 0
        for color in self.__colorList:
            if color == "black":
                index_black = index
            index += 1
            pix = QPixmap(70, 20)
            pix.fill(QColor(color))
            comboBox.addItem(QIcon(pix), color)
            comboBox.setIconSize(QSize(70, 20))
            comboBox.setSizeAdjustPolicy(QComboBox.AdjustToContents)

        comboBox.setCurrentIndex(index_black)

    def on_PenColorChange(self):
        color_index = self.__comboBox_penColor.currentIndex()
        color_str = self.__colorList[color_index]
        self.__paintBoard.ChangePenColor(color_str)

    def on_PenThicknessChange(self):
        penThickness = self.__spinBox_penThickness.value()
        self.__paintBoard.ChangePenThickness(penThickness)

    def on_btn_Save_Clicked(self):
        savePath = QFileDialog.getSaveFileName(self, 'Save Your Paint', '.\\',
                                               '*.png')
        print(savePath)
        if savePath[0] == "":
            print("Save cancel")
            return
        image = self.__paintBoard.GetContentAsQImage()
        image.save(savePath[0])

    def on_cbtn_Eraser_clicked(self):
        if self.__cbtn_Eraser.isChecked():
            self.__paintBoard.EraserMode = True  #Enter Eraser Mode [Note: The eraser mode does not work yet]
        else:
            self.__paintBoard.EraserMode = False  #Quit Eraser Mode

    # CAD functionalities
    def on_cbtn_DrawCircle_clicked(self):
        painter = QPainter(self)
        window = Dialog(['center', 'radias'])
        data = window.getData(['center', 'radias'])
        self.usingVP = False
        center_x = int(data[0].split(',')[0])
        center_y = int(data[0].split(',')[1])
        radias = int(data[1])
        self.__paintBoard.paintEllipse(center_x, center_y, radias, radias)

    def on_cbtn_DrawRect_clicked(self):
        painter = QPainter(self)
        window = Dialog(['center', 'upper left point'])
        data = window.getData(['center', 'upper left point'])
        self.usingVP = False
        center_x = int(data[0].split(',')[0])
        center_y = int(data[0].split(',')[1])
        upper_left_x = int(data[1].split(',')[0])
        upper_left_y = int(data[1].split(',')[1])
        self.__paintBoard.paintRect(center_x, center_y, upper_left_x,
                                    upper_left_y)

    def on_cbtn_DrawTriangle_clicked(self):
        painter = QPainter(self)
        window = Dialog(['point1', 'point2', 'point3'])
        data = window.getData(['point1', 'point2', 'point3'])
        self.usingVP = False
        P1_x = int(data[0].split(',')[0])
        P1_y = int(data[0].split(',')[1])
        P2_x = int(data[1].split(',')[0])
        P2_y = int(data[1].split(',')[1])
        P3_x = int(data[2].split(',')[0])
        P3_y = int(data[2].split(',')[1])
        points = QPolygon(
            [QPoint(P1_x, P1_y),
             QPoint(P2_x, P2_y),
             QPoint(P3_x, P3_y)])
        self.__paintBoard.paintTriangle(points)

    def on_cbtn_DrawLine_clicked(self):
        painter = QPainter(self)
        window = Dialog(['Point1', 'Point2'])
        data = window.getData(['Point1', 'Point2'])
        self.usingVP = False
        P1_x = int(data[0].split(',')[0])
        P1_y = int(data[0].split(',')[1])
        P2_x = int(data[1].split(',')[0])
        P2_y = int(data[1].split(',')[1])
        self.__paintBoard.paintLine(P1_x, P1_y, P2_x, P2_y)

    def on_cbtn_DrawArc_clicked(self):
        painter = QPainter(self)
        window = Dialog(['center', 'start point', 'end point'])
        data = window.getData(['center', 'start point', 'end point'])
        center_x = int(data[0].split(',')[0])
        center_y = int(data[0].split(',')[1])
        start_x = int(data[1].split(',')[0])
        start_y = int(data[1].split(',')[1])
        end_x = int(data[2].split(',')[0])
        end_y = int(data[2].split(',')[1])
        self.__paintBoard.paintArc(center_x, center_y, start_x, start_y, end_x,
                                   end_y)

    #10,20;20,30;90,40;60,70;90,90;130,150;100,120;130,190
    def on_cbtn_DrawBezierSpline_clicked(self):
        painter = QPainter(self)
        window = Dialog(['Points'])
        data = window.getData(['Points'])
        self.usingVP = False
        pointList = data[0].split(';')

        if (len(pointList) % 4 is not 0):
            print("Invalid point list!")
            return
        else:
            pointListX = []
            pointListY = []
            for i in range(len(pointList)):
                pointListX.append(pointList[i].split(',')[0])
                pointListY.append(pointList[i].split(',')[1])
            self.__paintBoard.paintBezierSpline(pointListX, pointListY)

    # Free drawing functionalities; also a state machine
    def free_draw_updates(self, penDataList):
        self.gcoordinate.emit(penDataList)
        lifted = penDataList[3]
        self.liftedDeque.append(lifted)
        # print(penDataList)
        # print("calling free_draw_updates")

        if penDataList is not None:
            # print(penDataList)
            # State 1: free drawing
            if (not (penDataList[0] < self.VPCoord_Start[0]
                     and penDataList[1] < self.VPCoord_Start[1])
                    and self.usingVP is False):
                self.penCoordinates[0] = penDataList[0]
                self.penCoordinates[1] = penDataList[1]
                self.penPressure = penDataList[2]
                # Check for relations
                for circle_x in list_circle_x:
                    if (abs(penDataList[0] - circle_x) < 10):
                        print("Same x, wanna stop?")
                for circle_y in list_circle_y:
                    if (abs(penDataList[1] - circle_y) < 10):
                        print("Same y, wanna stop?")

                #print("calling penMoveEvent" + str(self.liftedDeque) + str(penDataList))
                self.__paintBoard.penMoveEvent(self.penCoordinates,
                                               self.penPressure,
                                               self.liftedDeque)
                return

            # State 2: click with force within the VP boundary to begin using the VP functions
            elif (self.usingVP is False):  # penDataList[2] > 10 and
                '''
                self.penCoordinates[0] = penDataList[0]
                self.penCoordinates[1] = penDataList[1]
                self.penPressure = penDataList[2]
                '''
                #print(penDataList)
                pen_x = penDataList[0]
                pen_y = penDataList[1]
                pen_pressure = penDataList[2]
                self.usingMotor = False
                self.vpShapePointList = []
                self.vpPointCount = 0
                # lifted = True means the pen has been lifted
                # Check which region the pen is in and prepare enter different states accordingly
                if (pen_x < self.VPCoord_Circle[2]
                        and pen_y < self.VPCoord_Circle[3] and pen_x != 0
                        and lifted == True):
                    print("Circle")
                    self.usingVP = True
                    self.usingVP_Circle = True
                    self.vpShapePointList = []
                    self.vpPointCount = 0
                    self.BluetoothThread.beep()
                    time.sleep(0.5)
                    self.BluetoothThread.beep()
                    return
                    # self.on_cbtn_DrawCircle_clicked()

                elif (pen_x < self.VPCoord_Rect[2]
                      and pen_y < self.VPCoord_Rect[3] and lifted == True):
                    print("Rect")
                    self.usingVP = True
                    self.usingVP_Rect = True
                    self.vpShapePointList = []
                    self.vpPointCount = 0
                    self.BluetoothThread.beep()
                    time.sleep(0.5)
                    self.BluetoothThread.beep()
                    return

                elif (pen_x < self.VPCoord_Tri[2]
                      and pen_y < self.VPCoord_Tri[3] and lifted == True):
                    print("Tri")
                    self.usingVP = True
                    self.usingVP_Tri = True
                    self.vpShapePointList = []
                    self.vpPointCount = 0
                    self.BluetoothThread.beep()
                    time.sleep(0.5)
                    self.BluetoothThread.beep()
                    return

                elif (pen_x < self.VPCoord_Line[2]
                      and pen_y < self.VPCoord_Line[3] and lifted == True):
                    print("Line")
                    self.usingVP = True
                    self.usingVP_Line = True
                    self.vpShapePointList = []
                    self.vpPointCount = 0
                    self.BluetoothThread.beep()
                    time.sleep(0.5)
                    self.BluetoothThread.beep()
                    # return to prevent going further down
                    return

                elif (pen_x < self.VPCoord_Arc[2]
                      and pen_y < self.VPCoord_Arc[3] and lifted == True):
                    print("Arc")
                    self.usingVP = True
                    self.usingVP_Arc = True
                    self.vpShapePointList = []
                    self.vpPointCount = 0
                    self.BluetoothThread.beep()
                    time.sleep(0.5)
                    self.BluetoothThread.beep()
                    return

                elif (pen_x < self.VPCoord_Curve[2]
                      and pen_y < self.VPCoord_Curve[3] and lifted == True):
                    print("Bezier Curve")
                    self.usingVP = True
                    self.usingVP_Curve = True
                    self.vpShapePointList = []
                    self.vpPointCount = 0
                    self.BluetoothThread.beep()
                    time.sleep(0.5)
                    self.BluetoothThread.beep()
                    return

                elif (pen_x < self.VPCoord_Perspect[2]
                      and pen_y < self.VPCoord_Perspect[3] and lifted == True):
                    print("Perspective Drawing")
                    self.usingVP = True
                    self.usingVP_Perspect = True
                    self.usingVP_VPoint = True
                    self.vpShapePointList = []
                    self.vpPointCount = 0
                    self.BluetoothThread.beep()
                    time.sleep(0.5)
                    self.BluetoothThread.beep()
                    return

                elif (pen_x < self.VPCoord_Ruler[2]
                      and pen_y < self.VPCoord_Ruler[3] and lifted == True):
                    print("Ruler Mode")
                    self.usingVP = True
                    self.vpShapePointList = []
                    self.vpPointCount = 0
                    self.usingVP_Ruler = True
                    self.BluetoothThread.beep()
                    time.sleep(0.5)
                    self.BluetoothThread.beep()
                    return

                # Copy and Paste condition is currently not used. Put them in the end.
                #elif(pen_x < self.VPCoord_Perspect[2] and pen_y < self.VPCoord_Perspect[3] and lifted==True):
                #print("Ready to choose vanishing point")
                ## Upon user's every new click to start the copy, clear the previous list of points first
                #if(self.usingVP_Copy is False):
                #self.vpCopyPointList = []
                ## First click: start copying; second click: stop copying
                #self.usingVP = not self.usingVP
                #self.usingVP_Copy = not self.usingVP_Copy
                #return

                #elif(pen_x < self.VPCoord_Paste[2] and pen_y < self.VPCoord_Paste[3] and lifted==True):
                #print("Ready to paste")
                #self.usingVP = True
                #self.usingVP_Paste = True
                ## return to prevent going further down
                #return

            # State 2-a: Draw a circle/ellipse using VP function
            if (self.usingVP_Circle is True
                    and self.usingVP_Perspect is False):
                print(self.vpPointCount)
                # if the pen is lifted off the paper, append the last new point to the list
                if (lifted == True and self.vpPointCount < 2
                        and not (penDataList[0] < self.VPCoord_Start[0]
                                 and penDataList[1] < self.VPCoord_Start[1])):
                    self.vpPointCount += 1
                    print("Adding points to the list")
                    self.vpShapePointList.append(penDataList[0])
                    self.vpShapePointList.append(penDataList[1])
                    self.BluetoothThread.beep()

                if (self.vpPointCount >= 2):
                    print("drawing the circle")
                    radius = math.sqrt(
                        math.pow(
                            self.vpShapePointList[0] -
                            self.vpShapePointList[2], 2) + math.pow(
                                self.vpShapePointList[1] -
                                self.vpShapePointList[3], 2))
                    self.__paintBoard.paintEllipse(self.vpShapePointList[0],
                                                   self.vpShapePointList[1],
                                                   radius, radius)

                    # Add the x,y and radius to the list of circle
                    list_circle_x.append(self.vpShapePointList[0])
                    list_circle_y.append(self.vpShapePointList[1])
                    list_circle_r.append(radius)

                    # clear the flags and points data to go back to State 1
                    self.vpShapePointList = []
                    self.vpPointCount = 0
                    self.usingVP = False
                    self.usingVP_Circle = False
                    return

            # State 2-b: Draw a rectangle using VP function
            elif (self.usingVP_Rect is True
                  and self.usingVP_Perspect is False):
                print(self.vpPointCount)
                # if the pen is lifted off the paper, append the last new point to the list
                if (lifted == True and self.vpPointCount < 2
                        and not (penDataList[0] < self.VPCoord_Start[0]
                                 and penDataList[1] < self.VPCoord_Start[1])):
                    self.vpPointCount += 1
                    print("Adding points to the list")
                    self.vpShapePointList.append(penDataList[0])
                    self.vpShapePointList.append(penDataList[1])
                    self.BluetoothThread.beep()

                if (self.vpPointCount >= 2):
                    print("drawing the rect")
                    self.__paintBoard.paintRect(self.vpShapePointList[0],
                                                self.vpShapePointList[1],
                                                self.vpShapePointList[2],
                                                self.vpShapePointList[3])
                    # Emit the signal to the control thread, sending the 2 endpoints, current coordinates and force
                    controlRectList = self.vpShapePointList + penDataList
                    self.controlRectSignal.emit(controlRectList)
                    # clear the flags and points data to go back to State 1
                    #self.ControlThread.controlStartDrawRect()
                    self.vpPointCount = 0
                    self.usingVP = False
                    self.usingVP_Rect = False
                    return

            # The state to draw a perspective rectangle, still in progress
            # State 2-b-p: Draw a rectangle using VP function in perspective mode
            elif (self.usingVP_Rect is True and self.usingVP_Perspect is True):
                print(self.vpPointCount)
                # if the pen is lifted off the paper, append the last new point to the list
                if (lifted == True and self.vpPointCount < 2
                        and not (penDataList[0] < self.VPCoord_Start[0]
                                 and penDataList[1] < self.VPCoord_Start[1])):
                    self.vpPointCount += 1
                    print("Adding points to the list")
                    self.vpShapePointList.append(penDataList[0])
                    self.vpShapePointList.append(penDataList[1])
                    self.BluetoothThread.beep()

                if (self.vpPointCount >= 2):
                    print("drawing the rect in perspective")
                    print("the perspective coord is", self.vpVpoint)

                    #defining the orthogonal lines
                    ## line equation is y=ax+b a=
                    firstPoint = [
                        self.vpShapePointList[2], self.vpShapePointList[3]
                    ]
                    secondPoint = [
                        self.vpShapePointList[2], self.vpShapePointList[3] +
                        2 * abs(self.vpShapePointList[3] -
                                self.vpShapePointList[1])
                    ]
                    slop2 = (self.vpVpoint[1] - secondPoint[1]) / (
                        self.vpVpoint[0] - secondPoint[0])
                    y3rd = slop2 * (
                        2 * abs(self.vpShapePointList[2] -
                                self.vpShapePointList[0])) + secondPoint[1]
                    slop1 = (self.vpVpoint[1] - firstPoint[1]) / (
                        self.vpVpoint[0] - firstPoint[0])
                    y4th = slop1 * (
                        2 * abs(self.vpShapePointList[2] -
                                self.vpShapePointList[0])) + firstPoint[1]
                    thirdPoint = [
                        self.vpShapePointList[2] +
                        2 * abs(self.vpShapePointList[2] -
                                self.vpShapePointList[0]), y3rd
                    ]
                    fourthPoint = [
                        self.vpShapePointList[2] +
                        2 * abs(self.vpShapePointList[2] -
                                self.vpShapePointList[0]), y4th
                    ]

                    self.__paintBoard.paintPolyg(firstPoint[0], firstPoint[1],
                                                 secondPoint[0],
                                                 secondPoint[1], thirdPoint[0],
                                                 thirdPoint[1], fourthPoint[0],
                                                 fourthPoint[1])
                    # Emit the signal to the control thread, sending the 2 endpoints, current coordinates and force
                    controlRectPList = [
                        firstPoint[0], firstPoint[1], secondPoint[0],
                        secondPoint[1], thirdPoint[0], thirdPoint[1],
                        fourthPoint[0], fourthPoint[1]
                    ]
                    self.controlRectPSignal.emit(controlRectPList)
                    # clear the flags and points data to go back to State 1
                    #self.ControlThread.controlStartDrawRectP()
                    self.vpPointCount = 0
                    self.usingVP = False
                    self.usingVP_Rect = False
                    self.usingVP_Perspect = False
                    return

            # State 2-c: Draw a triangle using VP function
            elif (self.usingVP_Tri is True and self.usingVP_Perspect is False):
                print(self.vpPointCount)
                # if the pen is lifted off the paper, append the last new point to the list
                if (lifted == True and self.vpPointCount < 3
                        and not (penDataList[0] < self.VPCoord_Start[0]
                                 and penDataList[1] < self.VPCoord_Start[1])):
                    self.vpPointCount += 1
                    print("Adding points to the list")
                    self.vpShapePointList.append(penDataList[0])
                    self.vpShapePointList.append(penDataList[1])
                    self.BluetoothThread.beep()

                if (self.vpPointCount >= 3):
                    print("drawing the tri")
                    points = QPolygon([
                        QPoint(self.vpShapePointList[0],
                               self.vpShapePointList[1]),
                        QPoint(self.vpShapePointList[2],
                               self.vpShapePointList[3]),
                        QPoint(self.vpShapePointList[4],
                               self.vpShapePointList[5])
                    ])
                    self.__paintBoard.paintTriangle(points)
                    # clear the flags and points data to go back to State 1
                    controlTriList = [
                        self.vpShapePointList[0], self.vpShapePointList[1],
                        self.vpShapePointList[2], self.vpShapePointList[3],
                        self.vpShapePointList[4], self.vpShapePointList[5]
                    ]
                    self.controlTriSignal.emit(controlTriList)
                    #self.ControlThread.ControlStartDrawTri()
                    self.vpShapePointList = []
                    self.vpPointCount = 0
                    self.usingVP = False
                    self.usingVP_Tri = False
                    return

            # State 2-d: Draw a line using VP function
            elif (self.usingVP_Line is True
                  and self.usingVP_Perspect is False):
                print(self.vpPointCount)
                # if the pen is lifted off the papert and is outside of the virtual pallet, append the last new point to the list
                if (lifted == True and self.vpPointCount < 2
                        and not (penDataList[0] < self.VPCoord_Start[0] and
                                 penDataList[1] < self.VPCoord_Start[1])):  #
                    self.vpPointCount += 1
                    print("Adding points to the list")
                    self.vpShapePointList.append(penDataList[0])
                    self.vpShapePointList.append(penDataList[1])
                    self.BluetoothThread.beep()

                if (self.vpPointCount >= 2):
                    print("drawing the line")
                    if (len(self.vpShapePointList) >= 4):
                        self.__paintBoard.paintLine(self.vpShapePointList[0],
                                                    self.vpShapePointList[1],
                                                    self.vpShapePointList[2],
                                                    self.vpShapePointList[3])

                    # Emit the signal to the control thread, sending the 2 endpoints, current coordinates and force
                    controlLineList = self.vpShapePointList + penDataList
                    self.controlLineSignal.emit(controlLineList)

                    # clear the flags and points data to go back to State 1
                    # self.vpShapePointList = []
                    #self.ControlThread.controlStartDrawLine()
                    self.vpPointCount = 0
                    self.vpShapePointList = []
                    self.usingVP = False
                    self.usingVP_Line = False
                    self.usingMotor = True
                    self.usingMotor_Line = True
                    return

            # State 2-e: Draw an arc using VP function
            elif (self.usingVP_Arc is True and self.usingVP_Perspect is False):
                print(self.vpPointCount)
                # if the pen is lifted off the paper, append the last new point to the list
                if (lifted == True and self.vpPointCount < 3
                        and not (penDataList[0] < self.VPCoord_Start[0]
                                 and penDataList[1] < self.VPCoord_Start[1])):
                    self.vpPointCount += 1
                    print("Adding points to the list")
                    self.vpShapePointList.append(penDataList[0])
                    self.vpShapePointList.append(penDataList[1])
                    self.BluetoothThread.beep()

                if (self.vpPointCount >= 3):
                    print("drawing the arc")
                    self.__paintBoard.paintArc(self.vpShapePointList[0],
                                               self.vpShapePointList[1],
                                               self.vpShapePointList[2],
                                               self.vpShapePointList[3],
                                               self.vpShapePointList[4],
                                               self.vpShapePointList[5])
                    # clear the flags and points data to go back to State 1
                    self.vpShapePointList = []
                    self.vpPointCount = 0
                    self.usingVP = False
                    self.usingVP_Arc = False
                    return

            # State 2-f: Draw an Bezier curve using VP function
            elif (self.usingVP_Curve is True
                  and self.usingVP_Perspect is False):
                print(self.vpPointCount)
                # if the pen is lifted off the paper, append the last new point to the list
                if (lifted == True and self.vpPointCount < 4
                        and not (penDataList[0] < self.VPCoord_Start[0]
                                 and penDataList[1] < self.VPCoord_Start[1])):
                    self.vpPointCount += 1
                    print("Adding points to the list")
                    self.vpShapePointList.append(penDataList[0])
                    self.vpShapePointList.append(penDataList[1])
                    self.BluetoothThread.beep()

                if (self.vpPointCount == 4):
                    print("drawing the Bezier curve")
                    pointListX = [
                        self.vpShapePointList[0], self.vpShapePointList[2],
                        self.vpShapePointList[4], self.vpShapePointList[6]
                    ]
                    pointListY = [
                        self.vpShapePointList[1], self.vpShapePointList[3],
                        self.vpShapePointList[5], self.vpShapePointList[7]
                    ]
                    self.__paintBoard.paintBezierSpline(pointListX, pointListY)

                    # clear the flags and points data to go back to State 1
                    self.vpShapePointList = []
                    self.vpPointCount = 0
                    self.usingVP = False
                    self.usingVP_Curve = False
                    return

            # State 2-g: Defining the vanishing point
            elif (self.usingVP_VPoint is True):
                print(self.vpPointCount)
                # if the pen is lifted off the paper, append the last new point to the list
                if (lifted == True and self.vpPointCount < 2
                        and not (penDataList[0] < self.VPCoord_Start[0]
                                 and penDataList[1] < self.VPCoord_Start[1])):
                    self.vpPointCount += 1
                    print("Adding points to the list")
                    self.vpShapePointList.append(penDataList[0])
                    self.vpShapePointList.append(penDataList[1])
                    self.BluetoothThread.beep()

                if (self.vpPointCount == 1):
                    print("Vanishing point is set")
                    self.__paintBoard.paintEllipse(self.vpShapePointList[0],
                                                   self.vpShapePointList[1], 2,
                                                   2)
                    # clear the flags and points data to go back to State 1
                    self.vpVpoint = [
                        self.vpShapePointList[0], self.vpShapePointList[1]
                    ]
                    self.vpShapePointList = []
                    self.vpPointCount = 0
                    self.usingVP = False
                    self.usingVP_VPoint = False
                    return

            # State 2-h: Ruler Mode using VP function
            elif (self.usingVP_Ruler is True):
                print(self.vpPointCount)
                # if the pen is lifted off the papert and is outside of the virtual pallet, append the last new point to the list
                if (lifted == True and self.vpPointCount < 2
                        and not (penDataList[0] < self.VPCoord_Start[0] and
                                 penDataList[1] < self.VPCoord_Start[1])):  #
                    self.vpPointCount += 1
                    print("Adding points to the list")
                    self.vpShapePointList.append(penDataList[0])
                    self.vpShapePointList.append(penDataList[1])
                    self.BluetoothThread.beep()

                if (self.vpPointCount >= 2):
                    print("Ruler mode activated")
                    if (len(self.vpShapePointList) >= 4):
                        self.__paintBoard.paintLine(self.vpShapePointList[0],
                                                    self.vpShapePointList[1],
                                                    self.vpShapePointList[2],
                                                    self.vpShapePointList[3])

                    # Emit the signal to the control thread, sending the 2 endpoints, current coordinates and force
                    controlLineList = self.vpShapePointList + penDataList
                    self.controlLineSignal.emit(controlLineList)

                    # clear the flags and points data to go back to State 1
                    # self.vpShapePointList = []
                    #self.ControlThread.controlStartRuler()
                    self.vpPointCount = 0
                    self.vpShapePointList = []
                    self.usingVP = False
                    self.usingVP_Line = False
                    return

            # State 2-g: Copy a list of points of the shape being drawn by the user
            elif (self.usingVP_Copy is True
                  and self.usingVP_Perspect is False):
                # even index for x, odd index for y
                self.vpShapePointList.append(penDataList[0])
                self.vpShapePointList.append(penDataList[1])
                return

            # State 2-h: Paste a list of points of the shape drawn by the user
            elif (self.usingVP_Paste is True
                  and self.usingVP_Perspect is False):
                # even index for x, odd index for y
                if (lifted == True and self.vpPointCount < 4):
                    self.vpPointCount += 1
                    print("Adding points to the list")
                    self.vpShapePointList.append(penDataList[0])
                    self.vpShapePointList.append(penDataList[1])
                # iterate through the point list and draw the points on the canvas, starting from the new point the user clicked
                while (i < len(self.vpShapePointList) / 2):
                    coord = [
                        self.penCoordinates[i] - firstX + currentX,
                        self.penCoordinates[i + 1] - firstY + currentY
                    ]
                    self.__paintBoard.penMoveEvent(coord, 0)
                    i += 2

                self.usingVP = False
                self.usingVP_Paste = False
                return

            # State 2-i: Choosing a vanishing point on the paper. Must be put lastly in the if/else list
            elif (self.usingVP_Perspect is True):
                # even index for x, odd index for y
                if (lifted == True and self.vpPointCount < 1
                        and not (penDataList[0] < self.VPCoord_Start[0]
                                 and penDataList[1] < self.VPCoord_Start[1])):
                    self.vpPointCount += 1
                    print("Storing vanishing point")
                    self.vpVanishingPoint.append(penDataList[0])
                    self.vpVanishingPoint.append(penDataList[1])

                if (self.vpPointCount >= 1):
                    print("finished storing the vanishing point")
                    # clear the flags and points data to go back to State 1
                    self.vpPointCount = 0
                    return
                '''
                elif(pen_x < self.VPCoord_Arc[2] and pen_y < self.VPCoord_Arc[3]):
                    print("Arc")
                    self.usingVP = True
                    self.on_cbtn_DrawArc_clicked()
                elif(pen_x < self.VPCoord_BezierSpline[2] and pen_y < self.VPCoord_BezierSpline[3]):
                    print("BezierSpline")
                    self.usingVP = True
                    self.on_cbtn_DrawBezierSpline_clicked()
                '''

                #self.__paintBoard.penVPEvent(self.penCoordinates, self.penPressure)

            #state 3-d: Using the motor to draw a line with the start/end points obtained in state 2
            #if(self.usingMotor is True and self.usingMotor_Line is True):
            ##Emit the signal to the control thread, sending the 2 endpoints, current coordinates and force
            ##controlLineList = self.vpShapePointList + penDataList
            ##self.controlLineSignal.emit(controlLineList)
            #diffX = self.vpShapePointList[0] - penDataList[0]
            #diffY = self.vpShapePointList[1] - penDataList[1]
            #print("in state 3-d")

            ## show the real time drawing of the motor
            #self.penCoordinates[0] = penDataList[0]
            #self.penCoordinates[1] = penDataList[1]
            #self.penPressure = penDataList[2]
            #self.__paintBoard.penMoveEvent(self.penCoordinates, self.penPressure, self.liftedDeque)

            #if(abs(diffX) + abs(diffY) < 40):
            #self.vpShapePointList = []
            #self.usingVP = False
            #self.usingVP_Line = False
            #self.usingMotor = False
            #self.usingMotor_Line = True
            #self.ControlThread.controlStopDrawLine()

            #return

    def Quit(self):
        self.close()
class MainWidget(QWidget):
    def __init__(self, Parent=None):
        '''
        Constructor
        '''
        super().__init__(Parent)

        self.__InitData()  #先初始化数据,再初始化界面
        self.__InitView()

    def __InitData(self):
        '''
                  初始化成员变量
        '''
        self.__paintBoard = PaintBoard(self)
        self.__colorList = QColor.colorNames()  #获取颜色列表(字符串类型)

    def __InitView(self):
        '''
                  初始化界面
        '''
        self.setFixedSize(640, 480)
        self.setWindowTitle("PaintBoard Example PyQt5")

        main_layout = QHBoxLayout(self)  #新建一个水平布局作为本窗体的主布局
        main_layout.setSpacing(10)  #设置主布局内边距以及控件间距为10px

        main_layout.addWidget(self.__paintBoard)  #在主界面左侧放置画板

        sub_layout = QVBoxLayout()  #新建垂直子布局用于放置按键
        sub_layout.setContentsMargins(10, 10, 10, 10)  #设置此子布局和内部控件的间距为10px

        self.__btn_Clear = QPushButton("清空画板")
        self.__btn_Clear.setParent(self)  #设置父对象为本界面
        self.__btn_Clear.clicked.connect(
            self.__paintBoard.Clear)  #将按键按下信号与画板清空函数相关联
        sub_layout.addWidget(self.__btn_Clear)

        self.__label_digit = QLabel(self)
        self.__label_digit.resize(100, 30)
        self.__label_digit.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        # label1.setAutoFillBackground(True)
        # self.__btn_Quit = QPushButton("退出")
        # self.__btn_Quit.setParent(self) #设置父对象为本界面
        # self.__btn_Quit.clicked.connect(self.Quit)
        sub_layout.addWidget(self.__label_digit)

        self.__btn_Save = QPushButton("开始识别")
        self.__btn_Save.setParent(self)
        self.__btn_Save.clicked.connect(self.on_btn_Save_Clicked)
        sub_layout.addWidget(self.__btn_Save)

        self.__cbtn_Eraser = QCheckBox("  使用橡皮擦")
        self.__cbtn_Eraser.setParent(self)
        self.__cbtn_Eraser.clicked.connect(self.on_cbtn_Eraser_clicked)
        sub_layout.addWidget(self.__cbtn_Eraser)

        splitter = QSplitter(self)  #占位符
        sub_layout.addWidget(splitter)

        self.__label_penThickness = QLabel(self)
        self.__label_penThickness.setText("画笔粗细")
        self.__label_penThickness.setFixedHeight(20)
        sub_layout.addWidget(self.__label_penThickness)

        self.__spinBox_penThickness = QSpinBox(self)
        self.__spinBox_penThickness.setMaximum(20)
        self.__spinBox_penThickness.setMinimum(2)
        self.__spinBox_penThickness.setValue(10)  #默认粗细为10
        self.__spinBox_penThickness.setSingleStep(2)  #最小变化值为1
        self.__spinBox_penThickness.valueChanged.connect(
            self.on_PenThicknessChange
        )  #关联spinBox值变化信号和函数on_PenThicknessChange
        sub_layout.addWidget(self.__spinBox_penThickness)

        main_layout.addLayout(sub_layout)  #将子布局加入主布局

    def on_PenThicknessChange(self):
        penThickness = self.__spinBox_penThickness.value()
        self.__paintBoard.ChangePenThickness(penThickness)

    def on_btn_Save_Clicked(self):
        # savePath = QFileDialog.getSaveFileName(self, 'Save Your Paint', '.\\', '*.png')
        # print(savePath)
        # if savePath[0] == "":
        #     print("Save cancel")
        #     return
        image = self.__paintBoard.GetContentAsQImage()
        image.save("data/digit.png")
        t = recognition.recognition()
        self.digit = t.output()
        font = QtGui.QFont()
        # 字体
        font.setFamily('微软雅黑')
        # 加粗
        font.setBold(True)
        # 大小
        font.setPointSize(30)
        font.setWeight(75)
        self.__label_digit.setFont(font)
        self.__label_digit.setText("<font color=%s>%s</font>" %
                                   ('#7EC7FF', str(self.digit)))
        #self.__label_digit.setText(self.digit)
    def on_cbtn_Eraser_clicked(self):
        if self.__cbtn_Eraser.isChecked():
            self.__paintBoard.EraserMode = True  #进入橡皮擦模式
        else:
            self.__paintBoard.EraserMode = False  #退出橡皮擦模式

    def Quit(self):
        self.close()
示例#8
0
class MainWidget(QWidget):


    def __init__(self, Parent=None):
        '''
        Constructor
        '''
        super().__init__(Parent)
        
        self.__InitData() #先初始化数据,再初始化界面
        self.__InitView()
    
    def __InitData(self):
        '''
                  初始化成员变量
        '''
        self.__paintBoard = PaintBoard(self)
        self.__colorList = QColor.colorNames() #获取颜色列表(字符串类型)
        
    def __InitView(self):
        '''
                  初始化界面
        '''
        self.setFixedSize(2560,1600)
        self.setWindowTitle("图形学画板")
        

        main_layout = QHBoxLayout(self) #新建一个水平布局作为本窗体的主布局
        main_layout.setSpacing(10) #设置主布局内边距以及控件间距为10px

        sub_layout_LEVEL1 = QVBoxLayout() #新建垂直子布局用于放置按键
        sub_layout_LEVEL1.setContentsMargins(10, 10, 10, 10) #设置此子布局和内部控件的间距为10px
        main_layout.addLayout(sub_layout_LEVEL1) #将子布局1加入主布局

        sub_layout_LEVEL2 = QVBoxLayout()  # 新建垂直子布局用于放置按键
        sub_layout_LEVEL2.setContentsMargins(10, 10, 10, 10)  # 设置此子布局和内部控件的间距为10px
        main_layout.addLayout(sub_layout_LEVEL2)  # 将子布局2加入主布局

        sub_layout_LEVEL3 = QVBoxLayout()  # 新建垂直子布局用于放置按键
        sub_layout_LEVEL3.setContentsMargins(10, 10, 10, 10)  # 设置此子布局和内部控件的间距为10px
        main_layout.addLayout(sub_layout_LEVEL3)  # 将子布局2加入主布局

        sub_layout_LEVEL2_1 = QHBoxLayout()  # 新建水平子布局用于放置按键
        sub_layout_LEVEL2_1.setContentsMargins(10, 10, 10, 10)  # 设置此子布局和内部控件的间距为10px
        sub_layout_LEVEL2.addLayout(sub_layout_LEVEL2_1)

        sub_layout_LEVEL2_2 = QHBoxLayout()  # 新建水平子布局用于放置按键
        sub_layout_LEVEL2_2.setContentsMargins(10, 10, 10, 10)  # 设置此子布局和内部控件的间距为10px
        sub_layout_LEVEL2.addLayout(sub_layout_LEVEL2_2)

        sub_layout_LEVEL2_3 = QHBoxLayout()  # 新建水平子布局用于放置按键
        sub_layout_LEVEL2_3.setContentsMargins(10, 10, 10, 10)  # 设置此子布局和内部控件的间距为10px
        sub_layout_LEVEL2.addLayout(sub_layout_LEVEL2_3)

        sub_layout_LEVEL2_4 = QHBoxLayout()  # 新建水平子布局用于放置按键
        sub_layout_LEVEL2_4.setContentsMargins(10, 10, 10, 10)  # 设置此子布局和内部控件的间距为10px
        sub_layout_LEVEL2.addLayout(sub_layout_LEVEL2_4)

        #放置左侧图标
        self.__btn_Quit = QPushButton("    退出")
        self.__btn_Quit.setIcon(QIcon("1.png"))  # 设置图标
        self.__btn_Quit.setFixedHeight(60)
        self.__btn_Quit.setFixedWidth(200)
        self.__btn_Quit.setParent(self) #设置父对象为本界面
        self.__btn_Quit.clicked.connect(self.Quit)
        sub_layout_LEVEL1.addWidget(self.__btn_Quit)
        
        self.__btn_Save = QPushButton("保存作品")
        self.__btn_Save.setIcon(QIcon("1.png"))  # 设置图标
        self.__btn_Save.setFixedHeight(60)
        self.__btn_Save.setFixedWidth(200)
        self.__btn_Save.setParent(self)
        self.__btn_Save.clicked.connect(self.on_btn_Save_Clicked)
        sub_layout_LEVEL1.addWidget(self.__btn_Save)

        self.__btn_Load = QPushButton("读取作品")
        self.__btn_Load.setIcon(QIcon("1.png"))  # 设置图标
        self.__btn_Load.setFixedHeight(60)
        self.__btn_Load.setFixedWidth(200)
        self.__btn_Load.setParent(self)
        self.__btn_Load.clicked.connect(self.on_btn_Load_Clicked)
        sub_layout_LEVEL1.addWidget(self.__btn_Load)

        splitter = QSplitter(self) #占位符
        sub_layout_LEVEL1.addWidget(splitter)

        self.__cbtn_drawline=QPushButton("    直线")
        self.__cbtn_drawline.setIcon(QIcon("1.png"))  # 设置图标
        self.__cbtn_drawline.setFixedHeight(60)
        self.__cbtn_drawline.setFixedWidth(200)
        self.__cbtn_drawline.setParent(self)
        self.__cbtn_drawline.clicked.connect(self.on_cbtn_drawline_clicked)
        sub_layout_LEVEL1.addWidget(self.__cbtn_drawline)

        self.__cbtn_zhexian = QPushButton("    折线")
        self.__cbtn_zhexian.setIcon(QIcon("1.png"))  # 设置图标
        self.__cbtn_zhexian.setFixedHeight(60)
        self.__cbtn_zhexian.setFixedWidth(200)
        self.__cbtn_zhexian.setParent(self)
        self.__cbtn_zhexian.clicked.connect(self.on_cbtn_zhexian_clicked)
        sub_layout_LEVEL1.addWidget(self.__cbtn_zhexian)

        self.__cbtn_zhijiaoxian = QPushButton("  直角线")
        self.__cbtn_zhijiaoxian.setIcon(QIcon("1.png"))  # 设置图标
        self.__cbtn_zhijiaoxian.setFixedHeight(60)
        self.__cbtn_zhijiaoxian.setFixedWidth(200)
        self.__cbtn_zhijiaoxian.setParent(self)
        self.__cbtn_zhijiaoxian.clicked.connect(self.on_cbtn_zhijiaoxian_clicked)
        sub_layout_LEVEL1.addWidget(self.__cbtn_zhijiaoxian)

        self.__cbtn_duobianxing = QPushButton("  多边形")
        self.__cbtn_duobianxing.setIcon(QIcon("1.png"))  # 设置图标
        self.__cbtn_duobianxing.setFixedHeight(60)
        self.__cbtn_duobianxing.setFixedWidth(200)
        self.__cbtn_duobianxing.setParent(self)
        self.__cbtn_duobianxing.clicked.connect(self.on_cbtn_duobianxing_clicked)
        sub_layout_LEVEL1.addWidget(self.__cbtn_duobianxing)

        self.__cbtn_circle = QPushButton("  圆    ")
        self.__cbtn_circle.setIcon(QIcon("1.png"))  # 设置图标
        self.__cbtn_circle.setFixedHeight(60)
        self.__cbtn_circle.setFixedWidth(200)
        self.__cbtn_circle.setParent(self)
        self.__cbtn_circle.clicked.connect(self.on_cbtn_circle_clicked)
        sub_layout_LEVEL1.addWidget(self.__cbtn_circle)

        self.__cbtn_oval = QPushButton("    椭圆")
        self.__cbtn_oval.setIcon(QIcon("1.png"))  # 设置图标
        self.__cbtn_oval.setFixedHeight(60)
        self.__cbtn_oval.setFixedWidth(200)
        self.__cbtn_oval.setParent(self)
        self.__cbtn_oval.clicked.connect(self.on_cbtn_oval_clicked)
        sub_layout_LEVEL1.addWidget(self.__cbtn_oval)

        self.__cbtn_yuanhu = QPushButton("    圆弧")
        self.__cbtn_yuanhu.setIcon(QIcon("1.png"))  # 设置图标
        self.__cbtn_yuanhu.setFixedHeight(60)
        self.__cbtn_yuanhu.setFixedWidth(200)
        self.__cbtn_yuanhu.setParent(self)
        self.__cbtn_yuanhu.clicked.connect(self.on_cbtn_yuanhu_clicked)
        sub_layout_LEVEL1.addWidget(self.__cbtn_yuanhu)

        self.__cbtn_tuoyuanhu = QPushButton("  椭圆弧")
        self.__cbtn_tuoyuanhu.setIcon(QIcon("1.png"))  # 设置图标
        self.__cbtn_tuoyuanhu.setFixedHeight(60)
        self.__cbtn_tuoyuanhu.setFixedWidth(200)
        self.__cbtn_tuoyuanhu.setParent(self)
        self.__cbtn_tuoyuanhu.clicked.connect(self.on_cbtn_tuoyuanhu_clicked)
        sub_layout_LEVEL1.addWidget(self.__cbtn_tuoyuanhu)

        self.__cbtn_renyiquxian = QPushButton("任意曲线")
        self.__cbtn_renyiquxian.setIcon(QIcon("1.png"))  # 设置图标
        self.__cbtn_renyiquxian.setFixedHeight(60)
        self.__cbtn_renyiquxian.setFixedWidth(200)
        self.__cbtn_renyiquxian.setParent(self)
        self.__cbtn_renyiquxian.clicked.connect(self.on_cbtn_renyiquxian_clicked)
        sub_layout_LEVEL1.addWidget(self.__cbtn_renyiquxian)

        self.__cbtn_smooth_rectangle = QPushButton("圆角矩形")
        self.__cbtn_smooth_rectangle.setIcon(QIcon("1.png"))  # 设置图标
        self.__cbtn_smooth_rectangle.setFixedHeight(60)
        self.__cbtn_smooth_rectangle.setFixedWidth(200)
        self.__cbtn_smooth_rectangle.setParent(self)
        self.__cbtn_smooth_rectangle.clicked.connect(self.on_cbtn_smooth_rectangle_clicked)
        sub_layout_LEVEL1.addWidget(self.__cbtn_smooth_rectangle)

        self.__cbtn_rectangle = QPushButton("    矩形")
        self.__cbtn_rectangle.setIcon(QIcon("1.png"))  # 设置图标
        self.__cbtn_rectangle.setFixedHeight(60)
        self.__cbtn_rectangle.setFixedWidth(200)
        self.__cbtn_rectangle.setParent(self)
        self.__cbtn_rectangle.clicked.connect(self.on_cbtn_rectangle_clicked)
        sub_layout_LEVEL1.addWidget(self.__cbtn_rectangle)

        self.__cbtn_character = QPushButton("    字符")
        self.__cbtn_character.setIcon(QIcon("1.png"))  # 设置图标
        self.__cbtn_character.setFixedHeight(60)
        self.__cbtn_character.setFixedWidth(200)
        self.__cbtn_character.setParent(self)
        self.__cbtn_character.clicked.connect(self.on_cbtn_character_clicked)
        sub_layout_LEVEL1.addWidget(self.__cbtn_character)

        splitter = QSplitter(self) #占位符
        sub_layout_LEVEL1.addWidget(splitter)

        self.__cbtn_Eraser = QCheckBox("橡皮擦")
        self.__cbtn_Eraser.setIcon(QIcon("1.png"))  # 设置图标
        self.__cbtn_Eraser.setFixedHeight(60)
        self.__cbtn_Eraser.setFixedWidth(200)
        self.__cbtn_Eraser.setParent(self)
        self.__cbtn_Eraser.clicked.connect(self.on_cbtn_Eraser_clicked)
        sub_layout_LEVEL1.addWidget(self.__cbtn_Eraser)

        self.__btn_Clear = QPushButton("清空画板")
        self.__btn_Clear.setParent(self)  # 设置父对象为本界面
        self.__btn_Clear.setIcon(QIcon("1.png"))  # 设置图标
        self.__btn_Clear.setFixedHeight(60)
        self.__btn_Clear.setFixedWidth(200)
        self.__btn_Clear.clicked.connect(self.__paintBoard.Clear)  # 将按键按下信号与画板清空函数相关联
        sub_layout_LEVEL1.addWidget(self.__btn_Clear)

        splitter = QSplitter(self) #占位符
        sub_layout_LEVEL1.addWidget(splitter)

        self.__label_penThickness = QLabel(self)
        self.__label_penThickness.setText("画笔粗细")
        self.__label_penThickness.setFixedHeight(60)
        self.__label_penThickness.setFixedWidth(200)
        sub_layout_LEVEL1.addWidget(self.__label_penThickness)
        
        self.__spinBox_penThickness = QSpinBox(self)
        self.__spinBox_penThickness.setFixedHeight(60)
        self.__spinBox_penThickness.setFixedWidth(200)
        self.__spinBox_penThickness.setMaximum(20)
        self.__spinBox_penThickness.setMinimum(2)
        self.__spinBox_penThickness.setValue(10) #默认粗细为10
        self.__spinBox_penThickness.setSingleStep(2) #最小变化值为1
        self.__spinBox_penThickness.valueChanged.connect(self.on_PenThicknessChange)#关联spinBox值变化信号和函数on_PenThicknessChange
        sub_layout_LEVEL1.addWidget(self.__spinBox_penThickness)

        self.__label_penThickness = QLabel(self)
        self.__label_penThickness.setText("选择颜色")
        self.__label_penThickness.setFixedHeight(60)
        self.__label_penThickness.setFixedWidth(200)
        sub_layout_LEVEL1.addWidget(self.__label_penThickness)
        
        self.__comboBox_penColor = QComboBox(self)
        self.__comboBox_penColor.setFixedHeight(60)
        self.__comboBox_penColor.setFixedWidth(200)
        self.__fillColorList(self.__comboBox_penColor) #用各种颜色填充下拉列表
        self.__comboBox_penColor.currentIndexChanged.connect(self.on_PenColorChange) #关联下拉列表的当前索引变更信号与函数on_PenColorChange
        sub_layout_LEVEL1.addWidget(self.__comboBox_penColor)

        self.__btn_fillcolor = QPushButton("填充颜色")
        self.__btn_fillcolor.setIcon(QIcon("1.png"))  # 设置图标
        self.__btn_fillcolor.setFixedHeight(60)
        self.__btn_fillcolor.setFixedWidth(200)
        self.__btn_fillcolor.setParent(self)
        self.__btn_fillcolor.clicked.connect(self.on_btn_fillcolor_Clicked)
        sub_layout_LEVEL1.addWidget(self.__btn_fillcolor)

        #放置中间图标
        sub_layout_LEVEL2_2.addWidget(self.__paintBoard)#放置画板

        self.__cbtn_recall = QPushButton("    撤回")
        self.__cbtn_recall.setIcon(QIcon("1.png"))  # 设置图标
        self.__cbtn_recall.setFixedHeight(60)
        self.__cbtn_recall.setFixedWidth(200)
        self.__cbtn_recall.setParent(self)
        self.__cbtn_recall.clicked.connect(self.on_cbtn_recall_clicked)
        sub_layout_LEVEL2_3.addWidget(self.__cbtn_recall)

        self.__cbtn_repetition = QPushButton("    重复")
        self.__cbtn_repetition.setIcon(QIcon("1.png"))  # 设置图标
        self.__cbtn_repetition.setFixedHeight(60)
        self.__cbtn_repetition.setFixedWidth(200)
        self.__cbtn_repetition.setParent(self)
        self.__cbtn_repetition.clicked.connect(self.on_cbtn_repetition_clicked)
        sub_layout_LEVEL2_3.addWidget(self.__cbtn_repetition)

        self.__cbtn_aim_left = QPushButton("  左对齐")
        self.__cbtn_aim_left.setIcon(QIcon("1.png"))  # 设置图标
        self.__cbtn_aim_left.setFixedHeight(60)
        self.__cbtn_aim_left.setFixedWidth(200)
        self.__cbtn_aim_left.setParent(self)
        self.__cbtn_aim_left.clicked.connect(self.on_cbtn_aim_left_clicked)
        sub_layout_LEVEL2_1.addWidget(self.__cbtn_aim_left)

        self.__cbtn_aim_middle = QPushButton("中间对齐")
        self.__cbtn_aim_middle.setIcon(QIcon("1.png"))  # 设置图标
        self.__cbtn_aim_middle.setFixedHeight(60)
        self.__cbtn_aim_middle.setFixedWidth(200)
        self.__cbtn_aim_middle.setParent(self)
        self.__cbtn_aim_middle.clicked.connect(self.on_cbtn_aim_middle_clicked)
        sub_layout_LEVEL2_1.addWidget(self.__cbtn_aim_middle)

        self.__cbtn_aim_right = QPushButton("  右对齐")
        self.__cbtn_aim_right.setIcon(QIcon("1.png"))  # 设置图标
        self.__cbtn_aim_right.setFixedHeight(60)
        self.__cbtn_aim_right.setFixedWidth(200)
        self.__cbtn_aim_right.setParent(self)
        self.__cbtn_aim_right.clicked.connect(self.on_cbtn_aim_right_clicked)
        sub_layout_LEVEL2_1.addWidget(self.__cbtn_aim_right)

        self.__cbtn_cut_inside = QPushButton("  内裁剪")
        self.__cbtn_cut_inside.setIcon(QIcon("1.png"))  # 设置图标
        self.__cbtn_cut_inside.setFixedHeight(60)
        self.__cbtn_cut_inside.setFixedWidth(200)
        self.__cbtn_cut_inside.setParent(self)
        self.__cbtn_cut_inside.clicked.connect(self.on_cbtn_cut_inside_clicked)
        sub_layout_LEVEL2_4.addWidget(self.__cbtn_cut_inside)

        self.__cbtn_cut_outside = QPushButton("  外裁剪")
        self.__cbtn_cut_outside.setIcon(QIcon("1.png"))  # 设置图标
        self.__cbtn_cut_outside.setFixedHeight(60)
        self.__cbtn_cut_outside.setFixedWidth(200)
        self.__cbtn_cut_outside.setParent(self)
        self.__cbtn_cut_outside.clicked.connect(self.on_cbtn_cut_outside_clicked)
        sub_layout_LEVEL2_4.addWidget(self.__cbtn_cut_outside)

        #放置右侧图标

        self.__cbtn_select = QPushButton("    选择")
        self.__cbtn_select.setIcon(QIcon("1.png"))  # 设置图标
        self.__cbtn_select.setFixedHeight(60)
        self.__cbtn_select.setFixedWidth(200)
        self.__cbtn_select.setParent(self)
        self.__cbtn_select.clicked.connect(self.on_cbtn_select_clicked)
        sub_layout_LEVEL3.addWidget(self.__cbtn_select)

    def __fillColorList(self, comboBox):

        index_black = 0
        index = 0
        for color in self.__colorList: 
            if color == "black":
                index_black = index
            index += 1
            pix = QPixmap(70,20)
            pix.fill(QColor(color))
            comboBox.addItem(QIcon(pix),None)
            comboBox.setIconSize(QSize(70,20))
            comboBox.setSizeAdjustPolicy(QComboBox.AdjustToContents)

        comboBox.setCurrentIndex(index_black)
        
    def on_PenColorChange(self):
        color_index = self.__comboBox_penColor.currentIndex()
        color_str = self.__colorList[color_index]
        self.__paintBoard.ChangePenColor(color_str)

    def on_PenThicknessChange(self):
        penThickness = self.__spinBox_penThickness.value()
        self.__paintBoard.ChangePenThickness(penThickness)
    
    def on_btn_Save_Clicked(self):
        savePath = QFileDialog.getSaveFileName(self, 'Save Your Paint', '.\\', '*.png')
        print(savePath)
        if savePath[0] == "":
            print("Save cancel")
            return
        image = self.__paintBoard.GetContentAsQImage()
        image.save(savePath[0])
        
    def on_cbtn_Eraser_clicked(self):
        if self.__cbtn_Eraser.isChecked():
            self.__paintBoard.EraserMode = True #进入橡皮擦模式
        else:
            self.__paintBoard.EraserMode = False #退出橡皮擦模式
        
    def on_cbtn_drawline_clicked(self):
        print("划线函数")

    def on_btn_Load_Clicked(self):
        print("读取作品")

    def on_cbtn_zhexian_clicked(self):
        print("折线")

    def on_cbtn_zhijiaoxian_clicked(self):
        print("直角线")

    def on_cbtn_duobianxing_clicked(self):
        print("多边形")

    def on_cbtn_circle_clicked(self):
        print("圆")

    def on_cbtn_oval_clicked(self):
        print("椭圆")

    def on_cbtn_yuanhu_clicked(self):
        print("圆弧")

    def on_cbtn_tuoyuanhu_clicked(self):
        print("椭圆弧")

    def on_cbtn_renyiquxian_clicked(self):
        print("任意曲线")

    def on_cbtn_smooth_rectangle_clicked(self):
        print("圆角矩形")

    def on_cbtn_rectangle_clicked(self):
        print("矩形")

    def on_cbtn_character_clicked(self):
        print("字符")

    def on_cbtn_recall_clicked(self):
        print("撤回")

    def on_cbtn_repetition_clicked(self):
        print("重复")

    def on_cbtn_aim_left_clicked(self):
        print("左对齐")

    def on_cbtn_aim_middle_clicked(self):
        print("中间对齐")

    def on_cbtn_aim_right_clicked(self):
        print("右对齐")

    def on_cbtn_cut_inside_clicked(self):
        print("内裁剪")

    def on_cbtn_cut_outside_clicked(self):
        print("外裁剪")

    def on_cbtn_select_clicked(self):
        print("选择")

    def on_btn_fillcolor_Clicked(self):
        print("填充颜色")

    # def on_cbtn_drawline_clicked(self):
    #     print("划线函数")
    #
    # def on_cbtn_drawline_clicked(self):
    #     print("划线函数")
    #
    # def on_cbtn_drawline_clicked(self):
    #     print("划线函数")
    #
    # def on_cbtn_drawline_clicked(self):
    #     print("划线函数")
    #
    # def on_cbtn_drawline_clicked(self):
    #     print("划线函数")
    #
    # def on_cbtn_drawline_clicked(self):
    #     print("划线函数")

    def on_cbtn_drawline_clicked(self):
        print("划线函数")
    def Quit(self):
        self.close()
示例#9
0
class MainWidget(QWidget):


    def __init__(self, Parent=None):
        '''
        Constructor
        '''
        super().__init__(Parent)
        
        self.__InitData() #先初始化数据,再初始化界面
        self.__InitView()
    
    def __InitData(self):
        '''
                  初始化成员变量
        '''
        self.__paintBoard = PaintBoard(self)
        #获取颜色列表(字符串类型)
        self.__colorList = QColor.colorNames() 
        
    def __InitView(self):
        '''
                  初始化界面
        '''
        
        #新建一个水平布局作为本窗体的主布局
        main_layout = QHBoxLayout(self) 
        #设置主布局内边距以及控件间距为10px
        main_layout.setSpacing(10) 
    
        #在主界面左侧放置画板
        main_layout.addWidget(self.__paintBoard) 
        
        #新建垂直子布局用于放置按键
        sub_layout = QVBoxLayout() 
        
        
        #设置此子布局和内部控件的间距为10px
        sub_layout.setContentsMargins(10, 10, 10, 10) 

        self.__btn_Clear = QPushButton("清空画板")
        self.__btn_Clear.setParent(self) #设置父对象为本界面
       
        #将按键按下信号与画板清空函数相关联
        self.__btn_Clear.clicked.connect(self.__paintBoard.Clear) 
        sub_layout.addWidget(self.__btn_Clear)
        
        self.setFixedSize(660,480)
        self.setWindowTitle("手写数字识别")

        '''
        
        '''
        '''
        self.label_name = QLabel('江西理工大学', self)
        self.label_name.setGeometry(500,200,120,35)
        
        self.label_name = QLabel('信息工程学院', self)
        self.label_name.setGeometry(500,230,100,35)

        self.label_name = QLabel('电信172', self)
        self.label_name.setGeometry(500,260,100,35)

        self.label_name = QLabel('夏奥', self)
        self.label_name.setGeometry(500,290,100,35)
        '''

        self.label_name=QLabel('识别结果',self)
        self.label_name.setGeometry(500,200,100,35)


        self.__btn_Recognize=QPushButton("开始识别")
        self.__btn_Recognize.setParent(self)
        self.__btn_Recognize.clicked.connect(self.on_btn_Recognize_Clicked)
        sub_layout.addWidget(self.__btn_Recognize)

        self.__btn_Quit = QPushButton("退出")
        self.__btn_Quit.setParent(self) #设置父对象为本界面
        self.__btn_Quit.clicked.connect(self.Quit)
        sub_layout.addWidget(self.__btn_Quit)

        self.lcd_num=QLCDNumber(13,self)
        #self.lcd_num.resize(100,100)
        self.lcd_num.setDigitCount(1)
        self.lcd_num.move(500,400)
        sub_layout.addWidget(self.lcd_num)

        '''
        self.__btn_Save = QPushButton("保存作品")
        self.__btn_Save.setParent(self)
        self.__btn_Save.clicked.connect(self.on_btn_Save_Clicked)
        sub_layout.addWidget(self.__btn_Save)
        '''
        
        '''
        self.__cbtn_Eraser = QCheckBox("  使用橡皮擦")
        self.__cbtn_Eraser.setParent(self)
        self.__cbtn_Eraser.clicked.connect(self.on_cbtn_Eraser_clicked)
        sub_layout.addWidget(self.__cbtn_Eraser)
        '''
        
        splitter = QSplitter(self) #占位符
        sub_layout.addWidget(splitter)
        
        self.__label_penThickness = QLabel(self)
        self.__label_penThickness.setText("画笔粗细")
        self.__label_penThickness.setFixedHeight(20)
        sub_layout.addWidget(self.__label_penThickness)
        
        self.__spinBox_penThickness = QSpinBox(self)
        self.__spinBox_penThickness.setMaximum(60)
        self.__spinBox_penThickness.setMinimum(2)
        self.__spinBox_penThickness.setValue(30) #默认粗细为10
        self.__spinBox_penThickness.setSingleStep(2) #最小变化值为2
        self.__spinBox_penThickness.valueChanged.connect(self.on_PenThicknessChange)#关联spinBox值变化信号和函数on_PenThicknessChange
        sub_layout.addWidget(self.__spinBox_penThickness)
        
        self.__label_penColor = QLabel(self)
        self.__label_penColor.setText("画笔颜色")
        self.__label_penColor.setFixedHeight(20)
        sub_layout.addWidget(self.__label_penColor)
        
        self.__comboBox_penColor = QComboBox(self)
        self.__fillColorList(self.__comboBox_penColor) #用各种颜色填充下拉列表
        self.__comboBox_penColor.currentIndexChanged.connect(self.on_PenColorChange) #关联下拉列表的当前索引变更信号与函数on_PenColorChange
        sub_layout.addWidget(self.__comboBox_penColor)

        main_layout.addLayout(sub_layout) #将子布局加入主布局


    def __fillColorList(self, comboBox):

        index_black = 0
        index = 0
        for color in self.__colorList: 
            if color == "black":
                index_black = index
            index += 1
            pix = QPixmap(70,20)
            pix.fill(QColor(color))
            comboBox.addItem(QIcon(pix),None)
            comboBox.setIconSize(QSize(70,20))
            comboBox.setSizeAdjustPolicy(QComboBox.AdjustToContents)

        comboBox.setCurrentIndex(index_black)
        
    def on_PenColorChange(self):
        color_index = self.__comboBox_penColor.currentIndex()
        color_str = self.__colorList[color_index]
        self.__paintBoard.ChangePenColor(color_str)

    def on_PenThicknessChange(self):
        penThickness = self.__spinBox_penThickness.value()
        self.__paintBoard.ChangePenThickness(penThickness)
    
    '''
    def on_btn_Save_Clicked(self):
        savePath = QFileDialog.getSaveFileName(self, 'Save Your Paint', '.\\', '*.png')
        print(savePath)
        if savePath[0] == "":
            print("Save cancel")
            return
        image = self.__paintBoard.GetContentAsQImage()
        image.save(savePath[0])
    '''
    def on_cbtn_Eraser_clicked(self):
        if self.__cbtn_Eraser.isChecked():
            self.__paintBoard.EraserMode = True #进入橡皮擦模式
        else:
            self.__paintBoard.EraserMode = False #退出橡皮擦模式
    
    def on_btn_Recognize_Clicked(self):
        savePath = "C:/Users/夜了/.vscode/knn/pic/test.png"
        image = self.__paintBoard.GetContentAsQImage()
        #im=image.resize((48,48),Image.ANTIALIAS)
        image.save(savePath)
        print(savePath)
        ans=work()
        self.lcd_num.display(ans)

        
    def Quit(self):
        self.close()