프로젝트

일반

사용자정보

개정판 9f1fa28b

ID9f1fa28b3e125ebde8658d977dc7293c5c870d29
상위 ca6cd684
하위 aece692b

백흠경이(가) 5년 이상 전에 추가함

remove OcrResultDialog.py

Change-Id: Ie801fc3afb28c1839ee7af83d571eacce720deb5

차이점 보기:

DTI_PID/DTI_PID/App.py
96 96
    @history    18.04.23    Jeongwoo    Change method to execute ProjectDialog(dlg.exec_()→dlg.showDialog())
97 97
'''
98 98
if __name__ == '__main__':
99
    import cv2
100 99
    from License import QLicenseDialog
101 100
    from ProjectDialog import Ui_Dialog
102 101
    from MainWindow import MainWindow
DTI_PID/DTI_PID/AppDocData.py
6 6
import sqlite3
7 7
import datetime
8 8
from enum import Enum
9
from PIL import PngImagePlugin, JpegImagePlugin
10
from PIL import Image
11
from PIL.ImageQt import ImageQt
12 9

  
13 10
try:
14 11
    from PyQt5.QtCore import *
DTI_PID/DTI_PID/OcrResultDialog.py
1
# coding: utf-8
2
"""
3
    This is ocr result dialog module
4
"""
5
from PIL import Image
6
import io
7
import numpy as np
8
import math
9
from PyQt5.QtCore import *
10
from PyQt5.QtGui import *
11
from PyQt5.QtWidgets import *
12
import OcrResultDialog_UI
13
import QtImageViewer
14
import tesseract_ocr_module as TOCR
15
from App import App
16
from AppDocData import *
17

  
18
class QOcrResultDialog(QDialog):
19
    def __init__(self, parent, qimage, boundingBox, isModify = False, text = None):
20
        QDialog.__init__(self, parent)
21
        self.textInfoList = []
22

  
23
        self.isModify = isModify
24
        self.image = qimage
25
        self.originImageWidth = qimage.width()
26
        self.originImageHeight = qimage.height()
27
        self.boundingBox = boundingBox
28

  
29
        self.angle = 0 # angle is degree
30

  
31
        self.ui = OcrResultDialog_UI.Ui_Dialog()
32
        self.ui.setupUi(self)
33
        
34
        appDocData = AppDocData.instance()
35
        configs = appDocData.getAppConfigs('app', 'mode')
36
        if configs and 1 == len(configs) and 'advanced' == configs[0].value:
37
            pass
38
        else:
39
            self.ui.pushButtonMakeTrainingImage.setVisible(False)
40

  
41
        self.imgW = qimage.width()
42
        self.imgH = qimage.height()
43
        self.image = self.image.scaled(self.imgW, self.imgH)
44
        self.graphicsView = QtImageViewer.QtImageViewer(App.mainWnd())
45
        self.graphicsView.useDefaultCommand() ##### USE DEFAULT COMMAND
46
        self.graphicsView.setImage(self.image)
47
        self.ui.horizontalLayoutGraphicsView.addWidget(self.graphicsView)
48
        
49
        self.ui.counterClockPushButton_2.clicked.connect(lambda : self.rotateImage(True))
50
        self.ui.clockPushButton_2.clicked.connect(lambda : self.rotateImage(False))
51
        self.ui.redetectPushButton_2.clicked.connect(self.detectText)
52
        self.ui.pushButtonMakeTrainingImage.clicked.connect(self.pushButtonMakeTrainingImageClicked)
53

  
54
        if self.isModify == False:
55
            self.detectText()
56
        else:
57
            self.ui.detectResultTextEdit.setPlainText(text)
58

  
59
        self.isAccepted = False
60

  
61
    '''
62
        @brief      Make OCR Training Image
63
        @author     euisung
64
        @date       2018.10.16
65
        @history    euisung     2018.11.02       add notice push
66
    '''
67
    def pushButtonMakeTrainingImageClicked(self):
68
        import uuid
69
        uid = str(uuid.uuid4()) + '.png'
70
        appDocData = AppDocData.instance()
71
        project = appDocData.getCurrentProject()
72
        trainingImgPath = os.path.join(project.getTrainingFilePath(), uid)
73

  
74
        self.image.save(trainingImgPath)
75
        QMessageBox.about(self, self.tr("INFO"), self.tr('Successfully saved.'))
76
        QDialog.reject(self)
77
        
78
    def rotateImage(self, isCounterClock):
79
        for item in self.graphicsView.scene.items():
80
            self.graphicsView.scene.removeItem(item)
81
        self.graphicsView.clearImage()
82
        transform = QTransform()
83
        if isCounterClock:
84
            '''CounterClock'''
85
            self.angle = (self.angle - 90) % 360
86
            transform.rotate(-90)
87
        else:
88
            '''Clock'''
89
            self.angle = (self.angle - 270) % 360
90
            transform.rotate(90)
91
        #print(str(360 - self.angle))
92
        self.image = self.image.transformed(transform)
93
        self.graphicsView.setImage(self.image)
94
        self.textInfoList = []
95

  
96
    '''
97
        @history 2018.04.26 Jeongwoo    Add Rectangle with modified Coords
98
                 2018.06.20 Jeongwoo    Remove test code
99
                 2018.11.08 euisung     add white char list check process on db
100
                 2018.11.22 euisung     OCR lang apply fixed
101
    '''
102
    def detectText(self):
103
        try:
104
            buffer = QBuffer()
105
            buffer.open(QBuffer.ReadWrite)
106
            self.image.save(buffer, "PNG")
107
            pyImage = Image.open(io.BytesIO(buffer.data()))
108
            img = np.array(pyImage)
109
            
110
            #self.image.save('c:\\temp\\a.png')
111

  
112
            docData = AppDocData.instance()
113
            
114
            # get ocr data of area which has the text
115
            pt = self.boundingBox.center()
116
            areas = [area for area in docData.getAreaList() if area.contains((pt.x(), pt.y()))]
117
            ocr_data = sorted(areas, key=lambda attr: attr.area)[0].OCRData if areas else 'eng'
118
            # up to here
119

  
120
            whiteCharList = docData.getConfigs('Text Recognition', 'White Character List')
121
            if len(whiteCharList) is 0:
122
                self.textInfoList = TOCR.getTextInfo(img, (round(self.boundingBox.x()), round(self.boundingBox.y())), 0, language=ocr_data)
123
            else:
124
                self.textInfoList = TOCR.getTextInfo(img, (round(self.boundingBox.x()), round(self.boundingBox.y())), 0, language=ocr_data, conf = whiteCharList[0].value)
125

  
126
            if self.textInfoList is not None and len(self.textInfoList) > 0:
127
                self.ui.detectResultTextEdit.setText(self.getPlainText(self.textInfoList))
128
                for textInfo in self.textInfoList:
129
                    self.graphicsView.scene.addRect(textInfo.getX()-int(self.boundingBox.x()), textInfo.getY()-int(self.boundingBox.y()), textInfo.getW(), textInfo.getH(), QPen(Qt.red, 1, Qt.SolidLine))
130
            else:
131
                self.ui.detectResultTextEdit.setText("Not Found")
132
        except Exception as ex:
133
            from App import App 
134
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
135
            App.mainWnd().addMessage.emit(MessageType.Error, message)
136

  
137
    def getPlainText(self, textInfoList):
138
        text = ''
139
        for index in range(len(textInfoList)):
140
            textInfo = textInfoList[index]
141
            if index != 0:
142
                text = text + '\n'
143
            text = text + textInfo.getText()
144
        return text
145

  
146
    '''
147
        @brief      OK Button Clicked. Remake TextInfo object
148
        @author     Jeongwoo
149
        @date       18.04.19
150
        @history    18.04.20    Jeongwoo    Calculate Start Point Coordinates by rotated angle
151
                    18.04.26    Jeongwoo    Scene.itemAt(textX - boundBox.x(), textY - boundBox.y())
152
    '''
153
    def accept(self):
154
        self.isAccepted = True
155

  
156
        try:
157
            text = self.ui.detectResultTextEdit.toPlainText()
158
            if text == '' or text == 'Not Found':
159
                QMessageBox.about(self.ui.ocrDialogButtonBox, 'Notice', 'Please try again after recognition or type.')
160
                return
161

  
162
            splitText = text.split('\n')
163

  
164
            if not len(self.textInfoList) > 0:
165
                import cv2, sys
166
                from TextInfo import TextInfo
167
                #QMessageBox.about(self.ui.ocrDialogButtonBox, "알림", "텍스트 검출을 하신 후 다시 시도해주세요.")
168
                
169
                buffer = QBuffer()
170
                buffer.open(QBuffer.ReadWrite)
171
                self.image.save(buffer, "PNG")
172
                pyImage = Image.open(io.BytesIO(buffer.data()))
173
                img = np.array(pyImage)
174

  
175
                img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
176
                imgNot = np.ones(img.shape, np.uint8)
177
                cv2.bitwise_not(img, imgNot)
178
                imgNot = cv2.dilate(imgNot, np.ones((8,8), np.uint8))
179

  
180
                image, contours, hierarchy = cv2.findContours(imgNot, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
181
                minX, minY, maxX, maxY = sys.maxsize, sys.maxsize, 0 ,0
182
                if len(contours) is 0:
183
                    minX, minY, maxX, maxY = self.boundingBox.x(), self.boundingBox.y(), self.boundingBox.x() + self.image.width(), self.boundingBox.y() + self.image.height()
184
                else:
185
                    minX, minY, maxX, maxY = sys.maxsize, sys.maxsize, 0, 0
186
                    for cnt in contours:
187
                        x, y, w, h = cv2.boundingRect(cnt)
188
                        minX = min(x ,minX)
189
                        minY = min(y, minY)
190
                        maxX = max(x + w, maxX)
191
                        maxY = max(y + h, maxY)
192
                    minX, minY, maxX, maxY = minX + self.boundingBox.x(), minY + self.boundingBox.y(), maxX + self.boundingBox.x(), maxY + self.boundingBox.y()
193
                
194
                self.textInfoList.append(TextInfo(text, minX, minY, maxX - minX, maxY - minY, 0))
195

  
196
            if len(self.textInfoList) > 0:
197
                for index in range(len(splitText)):
198
                    textInfo = self.textInfoList[index]
199
                    item = self.graphicsView.scene.itemAt(QPointF(float(textInfo.getX() - int(self.boundingBox.x())), float(textInfo.getY()-int(self.boundingBox.y()))), QTransform())
200
                    if item is not None:
201
                        ## Transform rectangle for calculate start point
202
                        imgTransform = QTransform()
203
                        if self.angle == 90 or self.angle == 270:
204
                            imgTransform.translate(self.image.height()*0.5, self.image.width()*0.5)
205
                        elif self.angle == 0 or self.angle == 360:
206
                            imgTransform.translate(self.image.width()*0.5, self.image.height()*0.5)
207
                        imgTransform.rotate(-abs(self.angle))
208
                        imgTransform.translate(-self.image.width()*0.5, -self.image.height()*0.5)
209
                        rect = QRect(textInfo.getX() - int(self.boundingBox.x()), textInfo.getY() - int(self.boundingBox.y()), textInfo.getW(), textInfo.getH())
210
                        rect = imgTransform.mapRect(rect)
211
                        ## up to here
212
                        textInfo.setX(rect.x() + int(self.boundingBox.x()))
213
                        textInfo.setY(rect.y() + int(self.boundingBox.y()))
214
                        textInfo.setText(splitText[index])
215
                        radian = round(math.radians(abs(self.angle)), 2)
216
                        textInfo.setAngle(radian) # 360 degree == 6.28319 radian
217
                        if radian == 1.57 or radian == 4.71:
218
                            width = textInfo.getW()
219
                            height = textInfo.getH()
220
                            textInfo.setW(height) ## SWAP
221
                            textInfo.setH(width) ## SWAP
222
                self.textInfoList = self.textInfoList[:len(splitText)]
223

  
224
                QDialog.accept(self)
225

  
226
        except Exception as ex:
227
            from App import App 
228
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
229
            App.mainWnd().addMessage.emit(MessageType.Error, message)
230

  
231
    def reject(self):
232
        self.isAccepted = False
233
        self.textInfoList = None
234
        QDialog.reject(self)
235

  
236
    '''
237
        @brief  Display this QDialog
238
    '''
239
    def showDialog(self):
240
        #self.setWindowFlags(self.windowFlags() & ~Qt.WindowContextHelpButtonHint)
241
        self.exec_()
242
        return (self.isAccepted, self.textInfoList)
DTI_PID/DTI_PID/OcrResultDialog_UI.py
1
# -*- coding: utf-8 -*-
2

  
3
# Form implementation generated from reading ui file '.\UI\OcrResultDialog.ui'
4
#
5
# Created by: PyQt5 UI code generator 5.11.3
6
#
7
# WARNING! All changes made in this file will be lost!
8

  
9
from PyQt5 import QtCore, QtGui, QtWidgets
10

  
11
class Ui_Dialog(object):
12
    def setupUi(self, Dialog):
13
        Dialog.setObjectName("Dialog")
14
        Dialog.resize(1080, 650)
15
        Dialog.setMinimumSize(QtCore.QSize(1080, 650))
16
        font = QtGui.QFont()
17
        font.setFamily("맑은 고딕")
18
        font.setBold(True)
19
        font.setWeight(75)
20
        Dialog.setFont(font)
21
        self.gridLayout_2 = QtWidgets.QGridLayout(Dialog)
22
        self.gridLayout_2.setObjectName("gridLayout_2")
23
        self.splitter = QtWidgets.QSplitter(Dialog)
24
        self.splitter.setOrientation(QtCore.Qt.Vertical)
25
        self.splitter.setObjectName("splitter")
26
        self.topWidget = QtWidgets.QWidget(self.splitter)
27
        self.topWidget.setMinimumSize(QtCore.QSize(0, 150))
28
        self.topWidget.setObjectName("topWidget")
29
        self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.topWidget)
30
        self.verticalLayout_2.setContentsMargins(0, 0, 0, 0)
31
        self.verticalLayout_2.setObjectName("verticalLayout_2")
32
        self.tVerticalLayout_2 = QtWidgets.QVBoxLayout()
33
        self.tVerticalLayout_2.setObjectName("tVerticalLayout_2")
34
        self.horizontalLayout = QtWidgets.QHBoxLayout()
35
        self.horizontalLayout.setSizeConstraint(QtWidgets.QLayout.SetFixedSize)
36
        self.horizontalLayout.setContentsMargins(8, 8, 8, 8)
37
        self.horizontalLayout.setObjectName("horizontalLayout")
38
        self.targetTextLabel_2 = QtWidgets.QLabel(self.topWidget)
39
        self.targetTextLabel_2.setMinimumSize(QtCore.QSize(0, 60))
40
        self.targetTextLabel_2.setMaximumSize(QtCore.QSize(16777215, 60))
41
        font = QtGui.QFont()
42
        font.setBold(True)
43
        font.setWeight(75)
44
        self.targetTextLabel_2.setFont(font)
45
        self.targetTextLabel_2.setObjectName("targetTextLabel_2")
46
        self.horizontalLayout.addWidget(self.targetTextLabel_2)
47
        self.counterClockPushButton_2 = QtWidgets.QPushButton(self.topWidget)
48
        self.counterClockPushButton_2.setMinimumSize(QtCore.QSize(0, 60))
49
        self.counterClockPushButton_2.setMaximumSize(QtCore.QSize(60, 60))
50
        self.counterClockPushButton_2.setText("")
51
        icon = QtGui.QIcon()
52
        icon.addPixmap(QtGui.QPixmap(":/newPrefix/Rotate_Minus.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
53
        self.counterClockPushButton_2.setIcon(icon)
54
        self.counterClockPushButton_2.setIconSize(QtCore.QSize(32, 32))
55
        self.counterClockPushButton_2.setObjectName("counterClockPushButton_2")
56
        self.horizontalLayout.addWidget(self.counterClockPushButton_2)
57
        self.clockPushButton_2 = QtWidgets.QPushButton(self.topWidget)
58
        self.clockPushButton_2.setMinimumSize(QtCore.QSize(0, 60))
59
        self.clockPushButton_2.setMaximumSize(QtCore.QSize(60, 60))
60
        self.clockPushButton_2.setText("")
61
        icon1 = QtGui.QIcon()
62
        icon1.addPixmap(QtGui.QPixmap(":/newPrefix/Rotate_Plus.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
63
        self.clockPushButton_2.setIcon(icon1)
64
        self.clockPushButton_2.setIconSize(QtCore.QSize(32, 32))
65
        self.clockPushButton_2.setObjectName("clockPushButton_2")
66
        self.horizontalLayout.addWidget(self.clockPushButton_2)
67
        self.redetectPushButton_2 = QtWidgets.QPushButton(self.topWidget)
68
        self.redetectPushButton_2.setMinimumSize(QtCore.QSize(0, 60))
69
        self.redetectPushButton_2.setMaximumSize(QtCore.QSize(60, 60))
70
        self.redetectPushButton_2.setText("")
71
        icon2 = QtGui.QIcon()
72
        icon2.addPixmap(QtGui.QPixmap(":/newPrefix/OCR.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
73
        self.redetectPushButton_2.setIcon(icon2)
74
        self.redetectPushButton_2.setIconSize(QtCore.QSize(32, 32))
75
        self.redetectPushButton_2.setObjectName("redetectPushButton_2")
76
        self.horizontalLayout.addWidget(self.redetectPushButton_2)
77
        self.tVerticalLayout_2.addLayout(self.horizontalLayout)
78
        self.horizontalLayoutGraphicsView = QtWidgets.QHBoxLayout()
79
        self.horizontalLayoutGraphicsView.setObjectName("horizontalLayoutGraphicsView")
80
        self.tVerticalLayout_2.addLayout(self.horizontalLayoutGraphicsView)
81
        self.verticalLayout_2.addLayout(self.tVerticalLayout_2)
82
        self.bottomWidget = QtWidgets.QWidget(self.splitter)
83
        self.bottomWidget.setMinimumSize(QtCore.QSize(0, 150))
84
        self.bottomWidget.setObjectName("bottomWidget")
85
        self.verticalLayout_4 = QtWidgets.QVBoxLayout(self.bottomWidget)
86
        self.verticalLayout_4.setContentsMargins(0, 0, 0, 0)
87
        self.verticalLayout_4.setObjectName("verticalLayout_4")
88
        self.detectResultVerticalLayout_2 = QtWidgets.QVBoxLayout()
89
        self.detectResultVerticalLayout_2.setContentsMargins(8, 8, 8, 8)
90
        self.detectResultVerticalLayout_2.setObjectName("detectResultVerticalLayout_2")
91
        self.detectResultLabel_2 = QtWidgets.QLabel(self.bottomWidget)
92
        font = QtGui.QFont()
93
        font.setBold(True)
94
        font.setWeight(75)
95
        self.detectResultLabel_2.setFont(font)
96
        self.detectResultLabel_2.setObjectName("detectResultLabel_2")
97
        self.detectResultVerticalLayout_2.addWidget(self.detectResultLabel_2)
98
        self.detectResultTextEdit = QtWidgets.QTextEdit(self.bottomWidget)
99
        font = QtGui.QFont()
100
        font.setFamily("Consolas")
101
        font.setPointSize(15)
102
        self.detectResultTextEdit.setFont(font)
103
        self.detectResultTextEdit.setObjectName("detectResultTextEdit")
104
        self.detectResultVerticalLayout_2.addWidget(self.detectResultTextEdit)
105
        self.verticalLayout_4.addLayout(self.detectResultVerticalLayout_2)
106
        self.gridLayout_2.addWidget(self.splitter, 1, 0, 1, 1)
107
        self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
108
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
109
        self.pushButtonMakeTrainingImage = QtWidgets.QPushButton(Dialog)
110
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed)
111
        sizePolicy.setHorizontalStretch(0)
112
        sizePolicy.setVerticalStretch(0)
113
        sizePolicy.setHeightForWidth(self.pushButtonMakeTrainingImage.sizePolicy().hasHeightForWidth())
114
        self.pushButtonMakeTrainingImage.setSizePolicy(sizePolicy)
115
        self.pushButtonMakeTrainingImage.setObjectName("pushButtonMakeTrainingImage")
116
        self.horizontalLayout_2.addWidget(self.pushButtonMakeTrainingImage)
117
        self.ocrDialogButtonBox = QtWidgets.QDialogButtonBox(Dialog)
118
        self.ocrDialogButtonBox.setOrientation(QtCore.Qt.Horizontal)
119
        self.ocrDialogButtonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)
120
        self.ocrDialogButtonBox.setObjectName("ocrDialogButtonBox")
121
        self.horizontalLayout_2.addWidget(self.ocrDialogButtonBox)
122
        self.gridLayout_2.addLayout(self.horizontalLayout_2, 3, 0, 1, 1)
123

  
124
        self.retranslateUi(Dialog)
125
        self.ocrDialogButtonBox.accepted.connect(Dialog.accept)
126
        self.ocrDialogButtonBox.rejected.connect(Dialog.reject)
127
        QtCore.QMetaObject.connectSlotsByName(Dialog)
128

  
129
    def retranslateUi(self, Dialog):
130
        _translate = QtCore.QCoreApplication.translate
131
        Dialog.setWindowTitle(_translate("Dialog", "OCR"))
132
        self.targetTextLabel_2.setText(_translate("Dialog", "Recognition Object"))
133
        self.counterClockPushButton_2.setToolTip(_translate("Dialog", "반시계 방향 회전"))
134
        self.clockPushButton_2.setToolTip(_translate("Dialog", "시계 방향 회전"))
135
        self.detectResultLabel_2.setText(_translate("Dialog", "Recognition Result"))
136
        self.pushButtonMakeTrainingImage.setText(_translate("Dialog", "Save OCR Training Image"))
137

  
138
import MainWindow_rc
139

  
140
if __name__ == "__main__":
141
    import sys
142
    app = QtWidgets.QApplication(sys.argv)
143
    Dialog = QtWidgets.QDialog()
144
    ui = Ui_Dialog()
145
    ui.setupUi(Dialog)
146
    Dialog.show()
147
    sys.exit(app.exec_())
148

  

내보내기 Unified diff

클립보드 이미지 추가 (최대 크기: 500 MB)