프로젝트

일반

사용자정보

개정판 71e34951

ID71e34951c07bb5f496357435ed86cc5f4071a61e
상위 8744138e
하위 ed478827

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

issue #478: OCR Editor 로딩 시 이미지 맞춤
- OCR Editor의 분할 기능 수정

Change-Id: Ife6f83b440a60a3235e40d5da353930a9d3a66cc

차이점 보기:

DTI_PID/DTI_PID/AppDocData.py
1409 1409
                App.mainWnd().addMessage.emit(MessageType.Error, message)
1410 1410

  
1411 1411
    def saveAppConfigs(self, configs):
1412
        """
1413
        @brief      save application configurations
1414
        @author     humkyung
1415
        @date       2018.10.01
1416
        """
1412
        """save application configurations"""
1417 1413

  
1418 1414
        # Creates or opens a file called mydb with a SQLite3 DB
1419 1415
        dbPath = self.getAppDbPath()
1420
        conn = sqlite3.connect(dbPath)
1421
        with conn:
1416
        with sqlite3.connect(dbPath) as conn:
1422 1417
            try:
1423 1418
                # Get a cursor object
1424 1419
                cursor = conn.cursor()
DTI_PID/DTI_PID/MainWindow.py
1131 1131
            dialog = QOcrResultDialog(self.graphicsView, image, QRectF(x, y, width, height))
1132 1132
            (isAccept, textInfoList) = dialog.showDialog()
1133 1133
            if isAccept:
1134
                if textInfoList is not None and len(textInfoList) > 0:
1134
                if textInfoList:
1135 1135
                    for textInfo in textInfoList:
1136 1136
                        x = textInfo.getX()
1137 1137
                        y = textInfo.getY()
DTI_PID/DTI_PID/OcrResultDialog.py
47 47

  
48 48

  
49 49
class QOcrResultDialog(QDialog):
50
    def __init__(self, parent, qimage, boundingBox, isModify=False, text=None):
50
    def __init__(self, parent, qimage, boundingBox, text_item=None):
51 51
        QDialog.__init__(self, parent)
52 52
        self.textInfoList = []
53 53

  
54
        self.isModify = isModify
54
        self._text_item = text_item
55 55
        self.image = qimage
56
        #self.originImageWidth = qimage.width()
57
        #self.originImageHeight = qimage.height()
58 56
        self.boundingBox = boundingBox
59 57

  
60 58
        self.angle = 0  # angle is degree
......
63 61
        self.ui.setupUi(self)
64 62
        self.ui.detectResultTextEdit = SpellTextEdit()
65 63
        self.ui.detectResultTextEdit.setFont(QFont('Consolas', 15, QFont.Bold))
66
        self.ui.horizontalLayoutTextEdit.addWidget(self.ui.detectResultTextEdit, 0)
64
        self.ui.horizontalLayoutTextEdit.addWidget(self.ui.detectResultTextEdit)
67 65

  
68
        appDocData = AppDocData.instance()
69
        configs = appDocData.getAppConfigs('app', 'mode')
66
        app_doc_data = AppDocData.instance()
67
        configs = app_doc_data.getAppConfigs('app', 'mode')
70 68
        if configs and 1 == len(configs) and 'advanced' == configs[0].value:
71 69
            pass
72 70
        else:
73 71
            self.ui.pushButtonMakeTrainingImage.setVisible(False)
74 72

  
75
        #self.imgW = qimage.width()
76
        #self.imgH = qimage.height()
77
        #self.image = self.image.scaled(self.imgW, self.imgH)
78 73
        self.graphicsView = QtImageViewer.QtImageViewer(App.mainWnd())
79 74
        self.graphicsView.useDefaultCommand()  # USE DEFAULT COMMAND
80 75
        self.graphicsView.setImage(self.image)
81
        #self.graphicsView.zoomImage(False, event=None)
82 76
        self.ui.horizontalLayoutGraphicsView.addWidget(self.graphicsView)
83 77

  
84 78
        self.ui.counterClockPushButton_2.clicked.connect(lambda: self.rotateImage(True))
85 79
        self.ui.clockPushButton_2.clicked.connect(lambda: self.rotateImage(False))
86
        self.ui.redetectPushButton_2.clicked.connect(self.detectText)
80
        self.ui.redetectPushButton_2.clicked.connect(self.detect_text)
87 81
        self.ui.pushButtonMakeTrainingImage.clicked.connect(self.pushButtonMakeTrainingImageClicked)
88 82

  
89 83
        self.ui.comboBoxOCRData.addItem('eng')
90 84
        tessdata_path = os.path.join(os.getenv('ALLUSERSPROFILE'), 'Digital PID', 'Tesseract-OCR', 'tessdata')
91
        if os.path.isfile(os.path.join(tessdata_path, appDocData.getCurrentProject().getName() + '.traineddata')):
92
            self.ui.comboBoxOCRData.addItem(appDocData.getCurrentProject().getName())
85
        if os.path.isfile(os.path.join(tessdata_path, app_doc_data.getCurrentProject().getName() + '.traineddata')):
86
            self.ui.comboBoxOCRData.addItem(app_doc_data.getCurrentProject().getName())
93 87

  
94
        configs = appDocData.getConfigs('Text Recognition', 'OCR Data')
88
        configs = app_doc_data.getConfigs('Text Recognition', 'OCR Data')
95 89
        value = configs[0].value if 1 == len(configs) else ''
96 90
        if value:
97 91
            at = self.ui.comboBoxOCRData.findText(value)
......
99 93
        else:
100 94
            self.ui.comboBoxOCRData.selectedIndex = 0
101 95

  
102
        if not self.isModify:
103
            self.detectText()
96
        if not self._text_item:
97
            self.detect_text()
104 98
        else:
105
            self.ui.detectResultTextEdit.setPlainText(text)
99
            self.ui.detectResultTextEdit.setPlainText(self._text_item.text())
106 100
            self.ui.checkBoxSeperate.setChecked(False)
107 101

  
108 102
        self.isAccepted = False
109 103

  
104
    def showEvent(self, QShowEvent):
105
        """show event"""
106
        self.graphicsView.zoomImageInit()
107

  
110 108
    '''
111 109
        @brief      Make OCR Training Image
112 110
        @author     euisung
......
149 147
                 2018.11.08 euisung     add white char list check process on db
150 148
                 2018.11.22 euisung     OCR lang apply fixed
151 149
    '''
152
    def detectText(self):
150
    def detect_text(self):
153 151
        try:
154 152
            buffer = QBuffer()
155 153
            buffer.open(QBuffer.ReadWrite)
......
207 205
        try:
208 206
            text = self.ui.detectResultTextEdit.toPlainText()
209 207
            if text == '' or text == 'Not Found':
210
                QMessageBox.about(self.ui.ocrDialogButtonBox, 'Notice', 'Please try again after recognition or type.')
208
                QMessageBox.about(self.ui.ocrDialogButtonBox, self.tr('Notice'),
209
                                  self.tr('Please try again after recognition or type.'))
211 210
                return
212 211

  
213 212
            isSplit = self.ui.checkBoxSeperate.isChecked()
......
216 215
            else:
217 216
                splitText = [text]
218 217

  
219
            if not len(self.textInfoList) > 0:
220
                import cv2
221

  
222
                buffer = QBuffer()
223
                buffer.open(QBuffer.ReadWrite)
224
                self.image.save(buffer, "PNG")
225
                pyImage = Image.open(io.BytesIO(buffer.data()))
226
                img = np.array(pyImage)
227

  
228
                img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
229
                imgNot = np.ones(img.shape, np.uint8)
230
                cv2.bitwise_not(img, imgNot)
231
                imgNot = cv2.dilate(imgNot, np.ones((8, 8), np.uint8))
232

  
233
                contours, hierarchy = cv2.findContours(imgNot, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
234
                minX, minY, maxX, maxY = sys.maxsize, sys.maxsize, 0, 0
235
                if len(contours) is 0:
236
                    minX, minY, maxX, maxY = self.boundingBox.x(), self.boundingBox.y(), self.boundingBox.x() + self.image.width(), self.boundingBox.y() + self.image.height()
237
                else:
238
                    minX, minY, maxX, maxY = sys.maxsize, sys.maxsize, 0, 0
239
                    for cnt in contours:
240
                        x, y, w, h = cv2.boundingRect(cnt)
241
                        minX = min(x, minX)
242
                        minY = min(y, minY)
243
                        maxX = max(x + w, maxX)
244
                        maxY = max(y + h, maxY)
245
                    minX, minY, maxX, maxY = minX + self.boundingBox.x(), minY + self.boundingBox.y(), maxX + self.boundingBox.x(), maxY + self.boundingBox.y()
246

  
247
                self.textInfoList.append(TextInfo(text, minX, minY, maxX - minX, maxY - minY, 0))
218
            # try to detect text if there is no result of detection or
219
            # count of text info list not match with count of split text
220
            if not self.textInfoList or (len(self.textInfoList) != len(splitText)):
221
                self.detect_text()
248 222

  
249 223
            if not isSplit:
250 224
                minX, minY, maxX, maxY = sys.maxsize, sys.maxsize, 0, 0
......
257 231

  
258 232
                self.textInfoList = [TextInfo(text, minX, minY, maxX - minX, maxY - minY, 0)]
259 233

  
260
            if len(self.textInfoList) > 0:
261
                for index in range(len(splitText)):
262
                    textInfo = self.textInfoList[index]
263
                    item = self.graphicsView.scene.itemAt(QPointF(float(textInfo.getX() - int(self.boundingBox.x())),
264
                                                                  float(textInfo.getY() - int(self.boundingBox.y()))),
265
                                                          QTransform())
266
                    if item is not None:
267
                        # Transform rectangle for calculate start point
268
                        imgTransform = QTransform()
269
                        if self.angle == 90 or self.angle == 270:
270
                            imgTransform.translate(self.image.height() * 0.5, self.image.width() * 0.5)
271
                        elif self.angle == 0 or self.angle == 360:
272
                            imgTransform.translate(self.image.width() * 0.5, self.image.height() * 0.5)
273
                        imgTransform.rotate(-abs(self.angle))
274
                        imgTransform.translate(-self.image.width() * 0.5, -self.image.height() * 0.5)
275
                        rect = QRect(textInfo.getX() - int(self.boundingBox.x()),
276
                                     textInfo.getY() - int(self.boundingBox.y()), textInfo.getW(), textInfo.getH())
277
                        rect = imgTransform.mapRect(rect)
278
                        # up to here
279
                        textInfo.setX(rect.x() + int(self.boundingBox.x()))
280
                        textInfo.setY(rect.y() + int(self.boundingBox.y()))
281
                        textInfo.setText(splitText[index])
282
                        radian = round(math.radians(abs(self.angle)), 2)
283
                        textInfo.setAngle(radian)  # 360 degree == 6.28319 radian
284
                        if radian == 1.57 or radian == 4.71:
285
                            width = textInfo.getW()
286
                            height = textInfo.getH()
287
                            textInfo.setW(height)  # SWAP
288
                            textInfo.setH(width)  # SWAP
289
                self.textInfoList = self.textInfoList[:len(splitText)]
234
            if self.textInfoList:
235
                if self._text_item:
236
                    textInfo = self.textInfoList[0]
237
                    # Transform rectangle for calculate start point
238
                    imgTransform = QTransform()
239
                    if self.angle == 90 or self.angle == 270:
240
                        imgTransform.translate(self.image.height() * 0.5, self.image.width() * 0.5)
241
                    elif self.angle == 0 or self.angle == 360:
242
                        imgTransform.translate(self.image.width() * 0.5, self.image.height() * 0.5)
243
                    imgTransform.rotate(-abs(self.angle))
244
                    imgTransform.translate(-self.image.width() * 0.5, -self.image.height() * 0.5)
245
                    rect = QRect(textInfo.getX() - int(self.boundingBox.x()),
246
                                 textInfo.getY() - int(self.boundingBox.y()), textInfo.getW(), textInfo.getH())
247
                    rect = imgTransform.mapRect(rect)
248
                    # up to here
249
                    textInfo.setX(rect.x() + int(self.boundingBox.x()))
250
                    textInfo.setY(rect.y() + int(self.boundingBox.y()))
251
                    textInfo.setText(splitText[0])
252
                    radian = round(math.radians(abs(self.angle)), 2)
253
                    textInfo.setAngle(radian)  # 360 degree == 6.28319 radian
254
                    if radian == 1.57 or radian == 4.71:
255
                        width = textInfo.getW()
256
                        height = textInfo.getH()
257
                        textInfo.setW(height)  # SWAP
258
                        textInfo.setH(width)  # SWAP
259

  
260
                    self._text_item.setPlainText(splitText[0])
261
                    self._text_item.loc = [textInfo.getX(), textInfo.getY()]
262
                    self._text_item.size = (textInfo.getW(), textInfo.getH())
263
                    self._text_item.angle = radian
264
                    self._text_item.update_shape()
265

  
266
                    self.textInfoList = self.textInfoList[1:]
290 267

  
291 268
                QDialog.accept(self)
292 269

  
DTI_PID/DTI_PID/OcrResultDialog_UI.py
2 2

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

  
......
83 83
        spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
84 84
        self.gridLayout.addItem(spacerItem, 0, 1, 1, 1)
85 85
        self.tVerticalLayout_2.addLayout(self.gridLayout)
86
        spacerItem1 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
87
        self.tVerticalLayout_2.addItem(spacerItem1)
88 86
        self.horizontalLayoutGraphicsView = QtWidgets.QHBoxLayout()
87
        self.horizontalLayoutGraphicsView.setSizeConstraint(QtWidgets.QLayout.SetMaximumSize)
89 88
        self.horizontalLayoutGraphicsView.setObjectName("horizontalLayoutGraphicsView")
90 89
        self.tVerticalLayout_2.addLayout(self.horizontalLayoutGraphicsView)
91 90
        self.verticalLayout_2.addLayout(self.tVerticalLayout_2)
......
110 109
        self.detectResultLabel_2.setFont(font)
111 110
        self.detectResultLabel_2.setObjectName("detectResultLabel_2")
112 111
        self.horizontalLayout_3.addWidget(self.detectResultLabel_2)
113
        spacerItem2 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
114
        self.horizontalLayout_3.addItem(spacerItem2)
112
        spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
113
        self.horizontalLayout_3.addItem(spacerItem1)
115 114
        self.checkBoxSeperate = QtWidgets.QCheckBox(self.bottomWidget)
116 115
        self.checkBoxSeperate.setChecked(True)
117 116
        self.checkBoxSeperate.setObjectName("checkBoxSeperate")
DTI_PID/DTI_PID/Shapes/EngineeringTextItem.py
271 271
        QGraphicsTextItem.paint(self, painter, options, widget)
272 272

  
273 273
    '''
274
        @brief      Delete text item
275
        @author     Jeongwoo
276
        @date       2018.05.25
277
    '''
278

  
279
    def deleteTextItemFromScene(self):
280
        ''' not used '''
281
        # self.transfer.onRemoved.emit(self)
282
        self.scene().removeItem(self)
283

  
284
    '''
285 274
        @brief      Return real item position
286 275
        @author     Jeongwoo
287 276
        @date       2018.05.25
......
301 290
        try:
302 291
            dialog = QOcrResultDialog(None, self.scene().parent().image().copy(self.loc[0] - 3, self.loc[1] - 3,
303 292
                                                                               self.size[0] + 6, self.size[1] + 6),
304
                                      QRect(self.loc[0], self.loc[1], self.size[0], self.size[1]), True, self.text())
293
                                      QRect(self.loc[0], self.loc[1], self.size[0], self.size[1]), text_item=self)
305 294
            (isAccept, textInfoList) = dialog.showDialog()
306 295

  
307 296
            if isAccept:
308 297
                scene = self.scene()
309 298

  
310
                textInfo = textInfoList[0]
311
                x = textInfo.getX()
312
                y = textInfo.getY()
313
                angle = textInfo.getAngle()
314
                text = textInfo.getText()
315
                width = textInfo.getW()
316
                height = textInfo.getH()
317
                item = TextItemFactory.instance().createTextItem(textInfo)
318
                if item is not None:
319
                    item.loc = [x, y]
320
                    item.size = (width, height)
321
                    item.angle = angle
322
                    item.area = self.area
323
                    item.addTextItemToScene(scene)
324
                    item.transfer.onRemoved.connect(scene.parent().parent().parent().itemRemoved)
325

  
326
                    self.transfer.onRemoved.emit(self)
299
                # create new texts
300
                for text_info in textInfoList:
301
                    x = text_info.getX()
302
                    y = text_info.getY()
303
                    angle = text_info.getAngle()
304
                    text = text_info.getText()
305
                    width = text_info.getW()
306
                    height = text_info.getH()
307
                    item = TextItemFactory.instance().createTextItem(text_info)
308
                    if item is not None:
309
                        item.loc = [x, y]
310
                        item.size = (width, height)
311
                        item.angle = angle
312
                        item.area = self.area
313
                        item.addTextItemToScene(scene)
314
                        item.transfer.onRemoved.connect(scene.parent().parent().parent().itemRemoved)
327 315
        except Exception as ex:
328 316
            message = 'error occurred({}) in {}:{}'.format(self.tr('Fail to create text'),
329 317
                                                           sys.exc_info()[-1].tb_frame.f_code.co_filename,
......
389 377
        self.setTransform(transform)
390 378
        self.update()
391 379

  
392
    '''
393
        @brief      Put text on scene
394
        @author     Jeongwoo
395
        @date       18.04.23
396
        @history    humkyung 2018.06.30 apply font configuration
397
    '''
398
    def addTextItemToScene(self, scene):
380
    def update_shape(self):
381
        """update text shape"""
382

  
399 383
        try:
400 384
            app_doc_data = AppDocData.instance()
401 385
            configs = app_doc_data.getConfigs('Text Style', 'Font Name')
......
410 394
            x = self.loc[0]
411 395
            y = self.loc[1]
412 396
            rect = None
413
            lineCount = self.text().count('\n') if self.text().count('\n') is not 0 else 1
414
            transform = QTransform()
397
            line_count = self.text().count('\n') if self.text().count('\n') is not 0 else 1
415 398

  
416 399
            allowed_error = 0.001
417 400
            if abs(self.angle - 1.57) < allowed_error:
......
423 406
            else:
424 407
                self.angle = 0
425 408

  
409
            transform = QTransform()
426 410
            if abs(self.angle - 1.57) < allowed_error or abs(self.angle - 4.71) < allowed_error:
427 411
                font = QFont(fontName, width if fontSize == -1 else fontSize)
412
                font.setBold(True)
428 413

  
429 414
                x_factor = width / QFontMetricsF(font).height()
430
                y_factor = height / (QFontMetricsF(font).width(self.text()) / lineCount)
415
                y_factor = height / (QFontMetricsF(font).width(self.text()) / line_count)
431 416
                factor = min(x_factor, y_factor)
432 417
                font.setPointSizeF(font.pointSizeF() * factor)
433 418

  
434 419
                self.setFont(font)
435 420
                rect = self.boundingRect()
436
                sx = width / rect.height()
437
                sy = height / rect.width()
421
                sx = rect.height() / QFontMetricsF(font).height()
422
                text_width = (QFontMetricsF(font).width(self.text()) / line_count)
423
                sy = rect.width() / text_width
438 424

  
439
                transform.translate(x, y)
440
                transform.translate(width * 0.5, height * 0.5)
441
                transform.scale(1, sy)
425
                transform.translate(x + width * 0.5, y + height * 0.5)
442 426
                transform.rotateRadians(-self.angle)
427
                transform.scale(1, sy)
443 428
                transform.translate(-rect.width() * 0.5, -rect.height() * 0.5)
444 429
            elif abs(self.angle - 3.14) < allowed_error:
445 430
                font = QFont(fontName, height if fontSize == -1 else fontSize)
431
                font.setBold(True)
446 432

  
447
                x_factor = width / (QFontMetricsF(font).width(self.text()) / lineCount)
433
                x_factor = width / (QFontMetricsF(font).width(self.text()) / line_count)
448 434
                y_factor = height / QFontMetricsF(font).height()
449 435
                factor = min(x_factor, y_factor)
450 436
                font.setPointSizeF(font.pointSizeF() * factor)
451 437

  
452 438
                self.setFont(font)
453 439
                rect = self.boundingRect()
454
                sx = width / rect.width()
440
                sx = width / (QFontMetricsF(font).width(self.text()) / line_count)
455 441
                sy = height / rect.height()
456 442

  
457 443
                transform.translate(x, y - round((rect.height() - height) * 0.5))
......
460 446
                transform.translate(-width * 0.5, -height * 0.5)
461 447
            else:
462 448
                font = QFont(fontName, height if fontSize == -1 else fontSize)
449
                font.setBold(True)
463 450

  
464
                x_factor = width / (QFontMetricsF(font).width(self.text()) / lineCount)
451
                x_factor = width / (QFontMetricsF(font).width(self.text()) / line_count)
465 452
                y_factor = height / QFontMetricsF(font).height()
466 453
                factor = min(x_factor, y_factor)
467 454
                font.setPointSizeF(font.pointSizeF() * factor)
468 455

  
469 456
                self.setFont(font)
470
                rect = self.boundingRect()
471 457

  
472
                sx = width / rect.width()
473
                sy = height / rect.height()
458
                text_width = (QFontMetricsF(font).width(self.text()) / line_count)
459
                sx = width / text_width
460
                sy = height / QFontMetricsF(font).height()
474 461

  
475
                # if '\n' not in text:
476 462
                transform.translate(x, y)
477
                # transform.scale(sx, 1)
463
                #transform.scale(sx, 1)
478 464

  
479 465
            self.setTransform(transform)
480 466

  
481 467
            self.document().setDocumentMargin(0)
468
        except Exception as ex:
469
            from App import App
470
            from AppDocData import MessageType
471

  
472
            message = 'error occurred({}-{}) in {}:{}'.format(ex, self.text(),
473
                                                              sys.exc_info()[-1].tb_frame.f_code.co_filename,
474
                                                              sys.exc_info()[-1].tb_lineno)
475
            App.mainWnd().addMessage.emit(MessageType.Error, message)
476

  
477
    '''
478
        @brief      Put text on scene
479
        @author     Jeongwoo
480
        @date       18.04.23
481
        @history    humkyung 2018.06.30 apply font configuration
482
    '''
483
    def addTextItemToScene(self, scene):
484
        try:
485
            self.update_shape()
486
            """
482 487
            white_char_list = app_doc_data.getConfigs('Text Recognition', 'White Character List')
483
            #self.highlighter = Highlighter(self.document())
484
            #self.highlighter.white_char_list = white_char_list[0].value if white_char_list else None
488
            self.highlighter = Highlighter(self.document())
489
            self.highlighter.white_char_list = '‘' #white_char_list[0].value if white_char_list else None
490
            """
485 491

  
486 492
            scene.addItem(self)
487 493
        except Exception as ex:
DTI_PID/DTI_PID/TrainingEditorDialog.py
15 15
import AreaZoomCommand
16 16
import PlaceLineCommand
17 17

  
18

  
18 19
class QTrainingEditorDialog(QDialog):
19 20
    def __init__(self, parent, trainingImgPath, trainingBoxPath, boundaryOcrData, dateItem, boxItem):
20 21
        self.spinBoxFlag = False
......
44 45
        self.graphicsViewZoomDrawing.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
45 46
        self.graphicsViewZoomDrawing.setParent(self.ui.leftSideWidget)
46 47
        self.ui.horizontalLayoutZoomDrawing.addWidget(self.graphicsViewZoomDrawing)
47
        
48
        
48

  
49 49
        # 학습 이미지 읽어서 메인 뷰에 그림, 사이드 뷰에 추가
50 50
        try:
51
            #trainingImgPath = os.path.join(project.getTrainingFilePath(), 'seed.seedF.exp0.tif')
51
            # trainingImgPath = os.path.join(project.getTrainingFilePath(), 'seed.seedF.exp0.tif')
52 52
            cvImg = cv2.cvtColor(cv2.imread(trainingImgPath), cv2.COLOR_BGR2GRAY)
53
            cvImg = cv2.threshold(cvImg, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)[1]
53
            cvImg = cv2.threshold(cvImg, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
54 54
            bytesPerLine = cvImg.shape[1]
55 55
            image = QImage(cvImg.data, cvImg.shape[1], cvImg.shape[0], bytesPerLine, QImage.Format_Indexed8)
56 56

  
......
65 65
            self.graphicsViewZoomDrawing.setScene(scene)
66 66
            self._pixmapHandle = self.graphicsViewZoomDrawing.scene().addPixmap(pixmap)
67 67
            self.graphicsViewZoomDrawing.scene().setSceneRect(0, 0, pixmap.width(), pixmap.height())
68
            self.graphicsViewZoomDrawing.fitInView(self.graphicsViewZoomDrawing.scene().sceneRect(), Qt.KeepAspectRatioByExpanding)
68
            self.graphicsViewZoomDrawing.fitInView(self.graphicsViewZoomDrawing.scene().sceneRect(),
69
                                                   Qt.KeepAspectRatioByExpanding)
69 70
            rect = QGraphicsRectItem(0, 0, 0, 0)
70 71
            pen = QPen(Qt.SolidLine)
71 72
            pen.setColor(Qt.green)
......
76 77
            self.graphicsViewZoomDrawing.scene().addItem(rect)
77 78

  
78 79
        except Exception as ex:
79
            print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
80
            print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
81
                                                       sys.exc_info()[-1].tb_lineno))
80 82

  
81 83
        # 박스 읽어서 메인 뷰에 그림
82 84
        try:
......
92 94
            for box in boxList:
93 95
                if box == '': continue
94 96
                boxComponent = box.split(' ')
95
                singleBox = QTrainingBoxItem(str(boxComponent[0]), int(boxComponent[1]), cvImg.shape[0] - int(boxComponent[4]), int(boxComponent[3]) - int(boxComponent[1]), int(boxComponent[4]) - int(boxComponent[2]))
97
                singleBox = QTrainingBoxItem(str(boxComponent[0]), int(boxComponent[1]),
98
                                             cvImg.shape[0] - int(boxComponent[4]),
99
                                             int(boxComponent[3]) - int(boxComponent[1]),
100
                                             int(boxComponent[4]) - int(boxComponent[2]))
96 101
                singleBox.transfer.onRemoved.connect(self.itemRemoved)
97
                singleBox.addTextItemToScene(self.ui, self.graphicsViewTrainingDrawing, self.graphicsViewZoomDrawing, self.spinBoxFlag)
102
                singleBox.addTextItemToScene(self.ui, self.graphicsViewTrainingDrawing, self.graphicsViewZoomDrawing,
103
                                             self.spinBoxFlag)
98 104
        except Exception as ex:
99
            print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
105
            print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
106
                                                       sys.exc_info()[-1].tb_lineno))
100 107

  
101 108
        self.removedItems = []
102 109

  
......
117 124
        @author     euisung
118 125
        @date       2018.10.31
119 126
    '''
127

  
120 128
    def pushButtonSplitClicked(self):
121 129
        self.isChanged = True
122 130
        items = self.graphicsViewTrainingDrawing.scene.selectedItems()
123 131
        if len(items) is not 1:
124 132
            return
125 133
        rect = items[0].rect()
126
        secondBox = QTrainingBoxItem('', rect.x() + round(rect.width() / 2), rect.y(), round(rect.width() / 2), rect.height())
134
        secondBox = QTrainingBoxItem('', rect.x() + round(rect.width() / 2), rect.y(), round(rect.width() / 2),
135
                                     rect.height())
127 136
        secondBox.transfer.onRemoved.connect(self.itemRemoved)
128
        secondBox.addTextItemToScene(self.ui, self.graphicsViewTrainingDrawing, self.graphicsViewZoomDrawing, self.spinBoxFlag)
137
        secondBox.addTextItemToScene(self.ui, self.graphicsViewTrainingDrawing, self.graphicsViewZoomDrawing,
138
                                     self.spinBoxFlag)
129 139
        items[0].setRect(rect.x(), rect.y(), round(rect.width() / 2), rect.height())
130 140

  
131 141
    '''
......
133 143
        @author     euisung
134 144
        @date       2018.10.17
135 145
    '''
146

  
136 147
    def pushButtonAddClicked(self):
137 148
        self.isChanged = True
138 149
        items = self.graphicsViewTrainingDrawing.scene.selectedItems()
......
146 157
            for item in allItems:
147 158
                if type(item) is QGraphicsPixmapItem:
148 159
                    x = int(item.boundingRect().width() / 2)
149
                    y = int(item.boundingRect().height()/ 2)
160
                    y = int(item.boundingRect().height() / 2)
150 161
                elif hasattr(item, 'rect'):
151 162
                    count += 1
152 163
                    totalWidth += item.rect().width()
......
157 168
            for item in allItems:
158 169
                if type(item) is QGraphicsPixmapItem:
159 170
                    x = int(item.boundingRect().width() / 2)
160
                    y = int(item.boundingRect().height()/ 2)
171
                    y = int(item.boundingRect().height() / 2)
161 172
            rect = QRectF(x, y, 5, 10)
162 173
        singleBox = QTrainingBoxItem('', rect.x() + 3, rect.y(), rect.width(), rect.height())
163 174
        singleBox.transfer.onRemoved.connect(self.itemRemoved)
164
        singleBox.addTextItemToScene(self.ui, self.graphicsViewTrainingDrawing, self.graphicsViewZoomDrawing, self.spinBoxFlag)
175
        singleBox.addTextItemToScene(self.ui, self.graphicsViewTrainingDrawing, self.graphicsViewZoomDrawing,
176
                                     self.spinBoxFlag)
165 177

  
166 178
    '''
167 179
        @brief      delete boxitem by button click
168 180
        @author     euisung
169 181
        @date       2018.10.17
170 182
    '''
183

  
171 184
    def pushButtonDeleteClicked(self):
172 185
        self.isChanged = True
173 186
        items = self.graphicsViewTrainingDrawing.scene.selectedItems()
......
187 200
        @author     euisung
188 201
        @date       2018.10.17
189 202
    '''
203

  
190 204
    def pushButtonChangeClicked(self):
191 205
        self.isChanged = True
192 206
        items = self.graphicsViewTrainingDrawing.scene.selectedItems()
......
200 214
        @author     euisung
201 215
        @date       2018.10.17
202 216
    '''
217

  
203 218
    def pushButtonCancelClicked(self):
204 219
        if self.isChanged:
205
            reply = QMessageBox.question(self, self.tr('Continue?'), self.tr('Changes may not have been saved.'), QMessageBox.Ignore, QMessageBox.Cancel)
220
            reply = QMessageBox.question(self, self.tr('Continue?'), self.tr('Changes may not have been saved.'),
221
                                         QMessageBox.Ignore, QMessageBox.Cancel)
206 222
            if reply == QMessageBox.Ignore:
207 223
                QDialog.reject(self)
208 224
        else:
......
213 229
        @author     euisung
214 230
        @date       2018.10.16
215 231
    '''
232

  
216 233
    def pushButtonSaveClicked(self):
217 234
        items = self.graphicsViewTrainingDrawing.scene.items()
218 235
        outBox = ""
......
223 240
        for item in items:
224 241
            if type(item) is QTrainingBoxItem:
225 242
                rect = item.rect()
226
                char, x, y, width, height = item.char, int(rect.x()), int(rect.y()), int(rect.width()), int(rect.height())
243
                char, x, y, width, height = item.char, int(rect.x()), int(rect.y()), int(rect.width()), int(
244
                    rect.height())
227 245
                bx, by, bx2, by2 = str(x), str(imgHeight - y - height), str(x + width), str(imgHeight - y)
228 246
                if char == '':
229 247
                    continue
......
231 249
        fw = open(self.trainingBoxPath, 'w')
232 250
        fw.write(outBox)
233 251
        fw.close()
234
        modifiedTime = str(datetime.datetime.strptime(time.ctime(os.path.getmtime(self.trainingBoxPath)), "%a %b %d %H:%M:%S %Y"))
252
        modifiedTime = str(
253
            datetime.datetime.strptime(time.ctime(os.path.getmtime(self.trainingBoxPath)), "%a %b %d %H:%M:%S %Y"))
235 254
        self.dateItem.setText(modifiedTime)
236 255

  
237 256
        boxContent = outBox.split('\n')
......
242 261
        self.boxItem.setText(boxchars)
243 262

  
244 263
        self.isChanged = False
245
        reply = QMessageBox.information(self, self.tr('Information'), self.tr('Save Success!'), QMessageBox.Ok, QMessageBox.Cancel)
264
        reply = QMessageBox.information(self, self.tr('Information'), self.tr('Save Success!'), QMessageBox.Ok,
265
                                        QMessageBox.Cancel)
246 266
        if reply == QMessageBox.Ok:
247 267
            QDialog.reject(self)
248 268

  
......
251 271
        @author     euisung
252 272
        @date       2018.10.16
253 273
    '''
274

  
254 275
    def spinBoxChangedEvent(self, event):
255 276
        self.isChanged = True
256 277
        items = self.graphicsViewTrainingDrawing.scene.selectedItems()
......
270 291
            items[0].setPosCustom()
271 292
        elif spinBoxName == 'spinBoxWidth':
272 293
            spinBoxValue = self.ui.spinBoxWidth.value()
273
            items[0].setRect(QRectF(rect.x(),  rect.y(), spinBoxValue, rect.height()))
294
            items[0].setRect(QRectF(rect.x(), rect.y(), spinBoxValue, rect.height()))
274 295
            items[0].setPosCustom()
275 296
        elif spinBoxName == 'spinBoxHeight':
276 297
            spinBoxValue = self.ui.spinBoxHeight.value()
277 298
            items[0].setRect(QRectF(rect.x(), rect.y(), rect.width(), spinBoxValue))
278 299
            items[0].setPosCustom()
279 300

  
280
        rect = items[0].rect()        
301
        rect = items[0].rect()
281 302
        bound.setRect(rect)
282
        rectSide = QRectF(rect.x() - 3, rect.y() - 3, rect.width() + 6,  rect.height() + 6)
303
        rectSide = QRectF(rect.x() - 3, rect.y() - 3, rect.width() + 6, rect.height() + 6)
283 304
        self.graphicsViewZoomDrawing.fitInView(rectSide)
284 305
        self.graphicsViewTrainingDrawing.scene.update()
285
    
306

  
286 307
    def onAreaZoom(self, action):
287 308
        if self.ui.pushButtonZoom.isChecked():
288 309
            cmd = AreaZoomCommand.AreaZoomCommand(self.graphicsViewTrainingDrawing)
......
303 324

  
304 325
            if item.scene is not None: item.scene.removeItem(item)
305 326
        except Exception as ex:
306
            print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
327
            print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
328
                                                       sys.exc_info()[-1].tb_lineno))
307 329

  
308 330
    '''
309 331
        @brief      key pressed event
310 332
        @author     euisung
311 333
        @date       2018.11.05
312 334
    '''
335

  
313 336
    def keyPressEvent(self, event):
314 337
        try:
315 338
            items = self.graphicsViewTrainingDrawing.scene.selectedItems()
......
320 343
            x = selectedItem.rect().x()
321 344

  
322 345
            if event.key() == Qt.Key_Left:
323
                dx =  sys.maxsize
346
                dx = sys.maxsize
324 347
                for item in self.graphicsViewTrainingDrawing.scene.items():
325 348
                    if type(item) is QTrainingBoxItem:
326 349
                        if x - item.rect().x() > 0 and x - item.rect().x() < dx:
......
329 352
                if closestItem is not None:
330 353
                    closestItem.setSelected(True)
331 354
                    selectedItem.setSelected(False)
332
                    closestItem.mousePressEvent('arrow key')             
355
                    closestItem.mousePressEvent('arrow key')
333 356
            elif event.key() == Qt.Key_Right:
334 357
                dx = -sys.maxsize
335 358
                for item in self.graphicsViewTrainingDrawing.scene.items():
......
352 375
                text = event.text()
353 376
                if text: self.onCharChanged(text)
354 377
        except Exception as ex:
355
            print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
378
            print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
379
                                                       sys.exc_info()[-1].tb_lineno))
356 380
            from App import App
357 381
            from AppDocData import MessageType
358 382

  
359
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
383
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
384
                                                           sys.exc_info()[-1].tb_lineno)
360 385
            App.mainWnd().addMessage.emit(MessageType.Error, message)
361
            return None
386
            return None
DTI_PID/DTI_PID/TrainingEditor_UI.py
91 91
        self.verticalLayout_7.setObjectName("verticalLayout_7")
92 92
        self.gridLayout_2 = QtWidgets.QGridLayout()
93 93
        self.gridLayout_2.setObjectName("gridLayout_2")
94
        self.spinBoxWidth = QtWidgets.QSpinBox(self.leftSideWidget)
95
        self.spinBoxWidth.setMinimumSize(QtCore.QSize(80, 0))
96
        self.spinBoxWidth.setMaximumSize(QtCore.QSize(80, 16777215))
97
        self.spinBoxWidth.setMaximum(999999)
98
        self.spinBoxWidth.setObjectName("spinBoxWidth")
99
        self.gridLayout_2.addWidget(self.spinBoxWidth, 1, 1, 1, 1)
94
        self.lineEditChar = QtWidgets.QLineEdit(self.leftSideWidget)
95
        self.lineEditChar.setMinimumSize(QtCore.QSize(80, 0))
96
        self.lineEditChar.setMaximumSize(QtCore.QSize(80, 16777215))
97
        font = QtGui.QFont()
98
        font.setFamily("Consolas")
99
        self.lineEditChar.setFont(font)
100
        self.lineEditChar.setMaxLength(1)
101
        self.lineEditChar.setObjectName("lineEditChar")
102
        self.gridLayout_2.addWidget(self.lineEditChar, 2, 1, 1, 1)
103
        self.spinBoxTop = QtWidgets.QSpinBox(self.leftSideWidget)
104
        self.spinBoxTop.setMinimumSize(QtCore.QSize(80, 0))
105
        self.spinBoxTop.setMaximumSize(QtCore.QSize(80, 16777215))
106
        self.spinBoxTop.setMaximum(999999)
107
        self.spinBoxTop.setObjectName("spinBoxTop")
108
        self.gridLayout_2.addWidget(self.spinBoxTop, 0, 4, 1, 1)
100 109
        spacerItem3 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
101 110
        self.gridLayout_2.addItem(spacerItem3, 2, 3, 1, 1)
102 111
        self.spinBoxLeft = QtWidgets.QSpinBox(self.leftSideWidget)
......
111 120
        self.spinBoxLeft.setObjectName("spinBoxLeft")
112 121
        self.gridLayout_2.addWidget(self.spinBoxLeft, 0, 1, 1, 1)
113 122
        spacerItem4 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
114
        self.gridLayout_2.addItem(spacerItem4, 2, 4, 1, 1)
115
        self.lineEditChar = QtWidgets.QLineEdit(self.leftSideWidget)
116
        self.lineEditChar.setMinimumSize(QtCore.QSize(80, 0))
117
        self.lineEditChar.setMaximumSize(QtCore.QSize(80, 16777215))
118
        font = QtGui.QFont()
119
        font.setFamily("Consolas")
120
        self.lineEditChar.setFont(font)
121
        self.lineEditChar.setMaxLength(1)
122
        self.lineEditChar.setObjectName("lineEditChar")
123
        self.gridLayout_2.addWidget(self.lineEditChar, 2, 1, 1, 1)
123
        self.gridLayout_2.addItem(spacerItem4, 0, 2, 1, 1)
124 124
        self.label_6 = QtWidgets.QLabel(self.leftSideWidget)
125 125
        self.label_6.setObjectName("label_6")
126 126
        self.gridLayout_2.addWidget(self.label_6, 0, 3, 1, 1)
127 127
        self.label_7 = QtWidgets.QLabel(self.leftSideWidget)
128 128
        self.label_7.setObjectName("label_7")
129 129
        self.gridLayout_2.addWidget(self.label_7, 1, 3, 1, 1)
130
        spacerItem5 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
131
        self.gridLayout_2.addItem(spacerItem5, 2, 4, 1, 1)
130 132
        self.label_3 = QtWidgets.QLabel(self.leftSideWidget)
131 133
        self.label_3.setObjectName("label_3")
132 134
        self.gridLayout_2.addWidget(self.label_3, 0, 0, 1, 1)
135
        self.label_5 = QtWidgets.QLabel(self.leftSideWidget)
136
        self.label_5.setObjectName("label_5")
137
        self.gridLayout_2.addWidget(self.label_5, 1, 0, 1, 1)
138
        self.spinBoxWidth = QtWidgets.QSpinBox(self.leftSideWidget)
139
        self.spinBoxWidth.setMinimumSize(QtCore.QSize(80, 0))
140
        self.spinBoxWidth.setMaximumSize(QtCore.QSize(80, 16777215))
141
        self.spinBoxWidth.setMaximum(999999)
142
        self.spinBoxWidth.setObjectName("spinBoxWidth")
143
        self.gridLayout_2.addWidget(self.spinBoxWidth, 1, 1, 1, 1)
144
        self.label_4 = QtWidgets.QLabel(self.leftSideWidget)
145
        self.label_4.setObjectName("label_4")
146
        self.gridLayout_2.addWidget(self.label_4, 2, 0, 1, 1)
133 147
        self.spinBoxHeight = QtWidgets.QSpinBox(self.leftSideWidget)
134 148
        self.spinBoxHeight.setMinimumSize(QtCore.QSize(80, 0))
135 149
        self.spinBoxHeight.setMaximumSize(QtCore.QSize(80, 16777215))
136 150
        self.spinBoxHeight.setMaximum(999999)
137 151
        self.spinBoxHeight.setObjectName("spinBoxHeight")
138 152
        self.gridLayout_2.addWidget(self.spinBoxHeight, 1, 4, 1, 1)
139
        self.spinBoxTop = QtWidgets.QSpinBox(self.leftSideWidget)
140
        self.spinBoxTop.setMinimumSize(QtCore.QSize(80, 0))
141
        self.spinBoxTop.setMaximumSize(QtCore.QSize(80, 16777215))
142
        self.spinBoxTop.setMaximum(999999)
143
        self.spinBoxTop.setObjectName("spinBoxTop")
144
        self.gridLayout_2.addWidget(self.spinBoxTop, 0, 4, 1, 1)
145
        self.label_4 = QtWidgets.QLabel(self.leftSideWidget)
146
        self.label_4.setObjectName("label_4")
147
        self.gridLayout_2.addWidget(self.label_4, 2, 0, 1, 1)
148
        self.label_5 = QtWidgets.QLabel(self.leftSideWidget)
149
        self.label_5.setObjectName("label_5")
150
        self.gridLayout_2.addWidget(self.label_5, 1, 0, 1, 1)
151
        spacerItem5 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
152
        self.gridLayout_2.addItem(spacerItem5, 0, 2, 1, 1)
153 153
        self.verticalLayout_7.addLayout(self.gridLayout_2)
154
        spacerItem6 = QtWidgets.QSpacerItem(20, 30, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
154
        spacerItem6 = QtWidgets.QSpacerItem(300, 20, QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Minimum)
155 155
        self.verticalLayout_7.addItem(spacerItem6)
156
        spacerItem7 = QtWidgets.QSpacerItem(400, 20, QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Minimum)
157
        self.verticalLayout_7.addItem(spacerItem7)
158 156
        self.horizontalLayout_5 = QtWidgets.QHBoxLayout()
159 157
        self.horizontalLayout_5.setObjectName("horizontalLayout_5")
160
        spacerItem8 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
161
        self.horizontalLayout_5.addItem(spacerItem8)
158
        spacerItem7 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
159
        self.horizontalLayout_5.addItem(spacerItem7)
162 160
        self.pushButtonSave = QtWidgets.QPushButton(self.leftSideWidget)
163 161
        self.pushButtonSave.setMaximumSize(QtCore.QSize(80, 16777215))
164 162
        self.pushButtonSave.setObjectName("pushButtonSave")
......
196 194
        self.label_6.setText(_translate("TrainingEditorDialog", "Top"))
197 195
        self.label_7.setText(_translate("TrainingEditorDialog", "Height"))
198 196
        self.label_3.setText(_translate("TrainingEditorDialog", "Left"))
199
        self.label_4.setText(_translate("TrainingEditorDialog", "Character"))
200 197
        self.label_5.setText(_translate("TrainingEditorDialog", "Width"))
198
        self.label_4.setText(_translate("TrainingEditorDialog", "Character"))
201 199
        self.pushButtonSave.setText(_translate("TrainingEditorDialog", "Save"))
202 200
        self.pushButtonCancel.setText(_translate("TrainingEditorDialog", "Close"))
DTI_PID/DTI_PID/UI/OcrResultDialog.ui
188 188
          </layout>
189 189
         </item>
190 190
         <item>
191
          <spacer name="verticalSpacer">
192
           <property name="orientation">
193
            <enum>Qt::Vertical</enum>
191
          <layout class="QHBoxLayout" name="horizontalLayoutGraphicsView">
192
           <property name="sizeConstraint">
193
            <enum>QLayout::SetMaximumSize</enum>
194 194
           </property>
195
           <property name="sizeHint" stdset="0">
196
            <size>
197
             <width>20</width>
198
             <height>40</height>
199
            </size>
200
           </property>
201
          </spacer>
202
         </item>
203
         <item>
204
          <layout class="QHBoxLayout" name="horizontalLayoutGraphicsView"/>
195
          </layout>
205 196
         </item>
206 197
        </layout>
207 198
       </item>

내보내기 Unified diff

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