프로젝트

일반

사용자정보

개정판 ab1f8288

IDab1f828833201cecf7bebf02b8f0ffd250f7ec04
상위 ce386dc9
하위 360c8441

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

issue #641: drawing 객체를 받아 도면을 열도록 수정

Change-Id: I520596a6ec1ea0fe37937e6c1bd00954c34eec71

차이점 보기:

DTI_PID/DTI_PID/AppDocData.py
355 355
        self.imgName = os.path.splitext(os.path.basename(self._imgFilePath))[0]
356 356

  
357 357
    @staticmethod
358
    def my_imread(filePath):
358
    def my_imread(file_path):
359 359
        """ read a file which's name contains unicode string : ref http://devdoftech.co.kr:82/redmine/issues/631 """
360 360
        import numpy as np
361 361
        import cv2
362 362

  
363
        stream = open(filePath.encode('utf-8'), 'rb')
364
        _bytes = bytearray(stream.read())
365
        numpyArray = np.asarray(_bytes, dtype=np.uint8)
366
        return cv2.imdecode(numpyArray, cv2.IMREAD_UNCHANGED)
363
        _bytes = None
364
        with open(file_path.encode('utf-8'), 'rb') as stream:
365
            _bytes = bytearray(stream.read())
367 366

  
368
    '''
369
        @brief      getter of imgSrc
370
        @author     humkyung
371
        @date       2018.07.30
372
    '''
367
        numpyArray = np.asarray(_bytes, dtype=np.uint8)
368
        res = cv2.imdecode(numpyArray, cv2.IMREAD_UNCHANGED)
369
        return res
373 370

  
374 371
    @property
375 372
    def imgSrc(self):
376
        import cv2
377
        import numpy as np
373
        """return the image of active drawing"""
378 374

  
379
        if self._imgSrc is None and self._imgFilePath is not None and os.path.isfile(self._imgFilePath):
380
            self._imgSrc = cv2.cvtColor(AppDocData.my_imread(self._imgFilePath), cv2.COLOR_BGR2GRAY)
381
            self._imgSrc = cv2.threshold(self._imgSrc, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
382
            '''
383
            kernel = np.array([[-1, -1, -1],
384
                               [-1, 9, -1],
385
                               [-1, -1, -1]])
386
            self._imgSrc = cv2.filter2D(self._imgSrc, -1, kernel)
387
            # blur = cv2.GaussianBlur(self._imgSrc , (5,5), 0)
388
            # smooth = cv2.addWeighted(blur, 1.5, self._imgSrc, -0.5, 0)
389
            # self._imgSrc = cv2.threshold(smooth, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)[1]
390
            self._imgSrc = cv2.threshold(self._imgSrc, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
391
            '''
392

  
393
            configs = AppDocData.instance().getConfigs('Filter', 'DilateSize')
394
            if 1 == len(configs) and int(configs[0].value) is not 0:
395
                size = int(configs[0].value)
396
                kernel = np.ones((size, size), np.uint8)
397
                self._imgSrc = cv2.erode(self._imgSrc, kernel, iterations=1)
398

  
399
            configs = AppDocData.instance().getConfigs('Filter', 'FlatSize')
400
            if 1 == len(configs) and int(configs[0].value) is not 0:
401
                size = int(configs[0].value)
402
                kernel = np.ones((size, size), np.uint8)
403
                self._imgSrc = cv2.morphologyEx(self._imgSrc, cv2.MORPH_CLOSE, kernel)
404
                self._imgSrc = cv2.morphologyEx(self._imgSrc, cv2.MORPH_OPEN, kernel)
405

  
406
        return self._imgSrc
407

  
408
    '''
409
        @brief      setter of imgSrc
410
        @author     humkyung
411
        @date       2018.07.30
412
    '''
375
        if self.activeDrawing:
376
            return self.activeDrawing.image
377

  
378
        return None
413 379

  
414 380
    @imgSrc.setter
415 381
    def imgSrc(self, value):
416
        self._imgSrc = value
417

  
418
    '''
419
        @brief      reset imgSrc
420
        @author     humkyung
421
        @date       2018.07.30
422
    '''
382
        """set the image of active drawing with given value"""
423 383

  
424
    def resetImgSrc(self):
425
        self._imgSrc = None
384
        if self.activeDrawing:
385
            self.activeDrawing.image = value
426 386

  
427 387
    '''
428 388
        @brief  getter of line type configs
......
1979 1939

  
1980 1940
        return False
1981 1941

  
1942
    def read_drawing_shape(self, drawing):
1943
        """read drawing shape"""
1944

  
1945
        res = None
1946

  
1947
        with self.project.database.connect() as conn:
1948
            try:
1949
                # Get a cursor object
1950
                cursor = conn.cursor()
1951

  
1952
                sql = f"select Image from Drawings where UID='{drawing}'"
1953
                cursor.execute(sql)
1954
                records = cursor.fetchall()
1955
                for record in records:
1956
                    res = record[0]
1957
                    break
1958

  
1959
            # Catch the exception
1960
            except Exception as ex:
1961
                from App import App
1962
                # Roll back any change if something goes wrong
1963
                conn.rollback()
1964

  
1965
                message = 'error occurred({}) in {}:{}'.format(repr(ex), sys.exc_info()[-1].tb_frame.f_code.co_filename,
1966
                                                               sys.exc_info()[-1].tb_lineno)
1967
                App.mainWnd().addMessage.emit(MessageType.Error, message)
1968

  
1969
        return res
1970

  
1982 1971
    def read_symbol_shape(self, symbol_name):
1983 1972
        """read symbol shape(image and svg)"""
1984 1973

  
......
3443 3432

  
3444 3433
        res = []
3445 3434

  
3446
        conn = self.project.database.connect()
3447
        with conn:
3435
        with self.project.database.connect() as conn:
3448 3436
            try:
3449 3437
                cursor = conn.cursor() if self.project.database.db_type == 'SQLite' else conn.cursor(as_dict=True)
3450 3438
                sql = 'select UID,[NAME],[DATETIME] from Drawings'
......
3454 3442
            # Catch the exception
3455 3443
            except Exception as ex:
3456 3444
                from App import App
3457
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
3445
                message = 'error occurred({}) in {}:{}'.format(repr(ex), sys.exc_info()[-1].tb_frame.f_code.co_filename,
3458 3446
                                                              sys.exc_info()[-1].tb_lineno)
3459 3447
                App.mainWnd().addMessage.emit(MessageType.Error, message)
3460 3448

  
3461 3449
        return res
3462 3450

  
3463 3451
    def saveDrawings(self, drawings):
3464
        """
3465
        @brief      save drawings
3466
        @author     humkyung
3467
        @date       2018.11.03
3468
        """
3452
        """save given drawings"""
3469 3453

  
3470 3454
        import uuid
3471 3455

  
3472
        _drawings = self.getDrawings()
3473

  
3474
        conn = self.project.database.connect()
3475
        with conn:
3456
        with self.project.database.connect() as conn:
3476 3457
            try:
3477 3458
                # Get a cursor object
3478 3459
                cursor = conn.cursor() if self.project.database.db_type == 'SQLite' else conn.cursor(as_dict=True)
3460
                if self.project.database.db_type == 'SQLite':
3461
                    cursor.execute('begin')
3479 3462

  
3480 3463
                for drawing in drawings:
3481
                    matches = [draw for draw in _drawings if draw.UID == drawing.UID]
3482
                    if not matches:
3464
                    image_blob_data = None
3465
                    file_path = os.path.join(self.project.getDrawingFilePath(), drawing.name)
3466
                    if drawing.name and os.path.isfile(file_path):
3467
                        with open(file_path.encode('utf-8'), 'rb') as file:
3468
                            image_blob_data = file.read()
3469

  
3470
                    if drawing.UID is None:
3483 3471
                        sql = self.project.database.to_sql(
3484
                            'insert into Drawings(UID, [NAME], [DATETIME]) values(?, ?, ?)')
3485
                        param = tuple([str(uuid.uuid4()), drawing.name, ''])
3472
                            'insert into Drawings(UID, [NAME], [DATETIME], [Image]) values(?, ?, ?, ?)')
3473
                        param = tuple([str(uuid.uuid4()), drawing.name, '', image_blob_data])
3486 3474
                    else:
3487
                        sql = self.project.database.to_sql("update Drawings set [NAME]=?,[DATETIME]=? where UID=?")
3488
                        param = (drawing.name, drawing.datetime, str(drawing.UID))
3475
                        sql = self.project.database.to_sql("update Drawings set [NAME]=?,[DATETIME]=?,[Image]=? where UID=?")
3476
                        param = (drawing.name, drawing.datetime, image_blob_data, str(drawing.UID))
3489 3477

  
3490 3478
                    cursor.execute(sql, param)
3491
                conn.commit()
3479

  
3480
                if self.project.database.db_type == 'SQLite':
3481
                    cursor.execute('commit')
3482
                else:
3483
                    conn.commit()
3492 3484
            # Catch the exception
3493 3485
            except Exception as ex:
3494 3486
                # Roll back any change if something goes wrong
3495 3487
                conn.rollback()
3496 3488

  
3497 3489
                from App import App
3498
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
3490
                message = 'error occurred({}) in {}:{}'.format(repr(ex), sys.exc_info()[-1].tb_frame.f_code.co_filename,
3499 3491
                                                              sys.exc_info()[-1].tb_lineno)
3500 3492
                App.mainWnd().addMessage.emit(MessageType.Error, message)
3501 3493

  
DTI_PID/DTI_PID/Drawing.py
65 65
        ''' set drawing uid '''
66 66
        if not uid:
67 67
            drawings = app_doc_data.getDrawings()
68
            drawing = [drawing for drawing in drawings if self.name == os.path.splitext(drawing.name)[0]]
68
            drawing = [drawing for drawing in drawings if self.name == drawing.name]
69 69
            self.UID = drawing[0].UID if drawing else uuid.uuid4()
70 70
            self._datetime = drawing[0].datetime if drawing else None
71 71
        else:
72 72
            self.UID = uid
73 73

  
74
        self._image = None
74 75
        self.width = 0
75 76
        self.height = 0
76 77
        self._attrs = [['Drawing No', ''], ['Rev No', ''], ['Unit', '']]  # attributes
......
90 91
        """ set date time of drawing """
91 92
        self._datetime = value
92 93

  
94
    @property
95
    def file_path(self):
96
        """return file path"""
97

  
98
        app_doc_data = AppDocData.instance()
99
        return os.path.join(app_doc_data.project.getDrawingFilePath(), self.name)
100

  
101
    @property
102
    def contents(self):
103
        """getter of drawing image"""
104

  
105
        app_doc_data = AppDocData.instance()
106
        _bytes = app_doc_data.read_drawing_shape(self.UID)
107
        if _bytes: return _bytes
108

  
109
        file_path = os.path.join(app_doc_data.project.getDrawingFilePath(), self.name)
110
        if os.path.isfile(file_path):
111
            with open(file_path.encode('utf-8'), 'rb') as stream:
112
                _bytes = stream.read()
113

  
114
        return _bytes
115

  
116
    @property
117
    def image(self):
118
        """return the image of drawing"""
119

  
120
        import cv2
121
        import numpy as np
122

  
123
        if self._image is None:
124
            numpyArray = np.asarray(bytearray(self.contents), dtype=np.uint8)
125
            image = cv2.imdecode(numpyArray, cv2.IMREAD_UNCHANGED)
126
            self._image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
127
            self._image = cv2.threshold(self._image, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
128

  
129
            app_doc_data = AppDocData.instance()
130
            configs = app_doc_data.getConfigs('Filter', 'DilateSize')
131
            if 1 == len(configs) and int(configs[0].value) is not 0:
132
                size = int(configs[0].value)
133
                kernel = np.ones((size, size), np.uint8)
134
                self._image = cv2.erode(self._image, kernel, iterations=1)
135

  
136
            configs = app_doc_data.getConfigs('Filter', 'FlatSize')
137
            if 1 == len(configs) and int(configs[0].value) is not 0:
138
                size = int(configs[0].value)
139
                kernel = np.ones((size, size), np.uint8)
140
                self._image = cv2.morphologyEx(self._image, cv2.MORPH_CLOSE, kernel)
141
                self._image = cv2.morphologyEx(self._image, cv2.MORPH_OPEN, kernel)
142

  
143
        return self._image
144

  
145
    @image.setter
146
    def image(self, value):
147
        """set drawing's image"""
148

  
149
        self._image = None
150

  
93 151
    '''
94 152
        @brief  getter of attrs
95 153
        @author humkyung
DTI_PID/DTI_PID/MainWindow.py
66 66
from DisplayColors import DisplayColors
67 67
from DisplayColors import DisplayOptions
68 68
import uuid
69
from openpyxl import *
70
from openpyxl.styles import *
71 69

  
72 70

  
73 71
class MainWindow(QMainWindow, MainWindow_UI.Ui_MainWindow, SingletonInstane):
......
136 134
        else:
137 135
            at = self.lineComboBox.findText('Secondary')
138 136
            self.lineComboBox.setCurrentIndex(at)
139
        #self.lineComboBox.currentIndexChanged.connect(self.onLineTypeChanged)
137
        # self.lineComboBox.currentIndexChanged.connect(self.onLineTypeChanged)
140 138

  
141 139
        self.toolBar.insertWidget(self.actionOCR, self.lineComboBox)
142 140
        self.toolBar.insertSeparator(self.actionOCR)
......
160 158
        self._display_widget.setLayout(layout)
161 159
        self.EditToolbar.insertWidget(None, self._display_widget)
162 160
        self._by_line_no.setChecked(
163
            True) if DisplayColors.instance().option == DisplayOptions.DisplayByLineNo else self._by_line_type.setChecked(
164
            True)
161
            True) if DisplayColors.instance().option == DisplayOptions.DisplayByLineNo else \
162
            self._by_line_type.setChecked(True)
165 163

  
166 164
        self.verticalLayout.addWidget(self.graphicsView)
167 165

  
......
216 214

  
217 215
        # connect signals and slots
218 216
        self.actionClose.triggered.connect(self.close)
219
        self.actionOpen.triggered.connect(self.onOpenImageDrawing)
217
        self.actionOpen.triggered.connect(self.open_image_drawing)
220 218
        self.actionLine.triggered.connect(self.onPlaceLine)
221 219
        self.actionRecognition.triggered.connect(self.recognize)
222 220
        self.pushButtonBatchRecognition.clicked.connect(self.recognizeBatch)
......
261 259
        self.addMessage.connect(self.onAddMessage)
262 260
        self.actionFindReplaceText.triggered.connect(self.findReplaceTextClicked)
263 261
        self.pushButtonDetectSymbol.clicked.connect(self.show_detect_symbol_dialog)
264
        #self.graphicsView.scene.contents_changed.connect(self.scene_changed)
262
        # self.graphicsView.scene.contents_changed.connect(self.scene_changed)
265 263

  
266 264
        configs = docData.getAppConfigs('app', 'mode')
267 265
        if configs and 1 == len(configs) and 'advanced' == configs[0].value:
......
352 350
                self.tableWidgetInconsistency.removeRow(row)
353 351
        except Exception as ex:
354 352
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
355
                                                          sys.exc_info()[-1].tb_lineno)
353
                                                           sys.exc_info()[-1].tb_lineno)
356 354
            self.addMessage.emit(MessageType.Error, message)
357 355
        # finally:
358 356
        #    return QTableView.keyPressEvent(self.tableWidgetInconsistency, event)
......
388 386
                self.makeInconsistencyTableRow(index, errors[index])
389 387
        except Exception as ex:
390 388
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
391
                                                          sys.exc_info()[-1].tb_lineno)
389
                                                           sys.exc_info()[-1].tb_lineno)
392 390
            self.addMessage.emit(MessageType.Error, message)
393 391

  
394 392
    def makeInconsistencyTableRow(self, row, errorItem):
......
481 479
            self.treeWidgetDrawingList.root.setCheckState(0, Qt.Unchecked)
482 480
            files = app_doc_data.getDrawingFileList()
483 481
            for file in files:
484
                drawing = [drawing for drawing in drawings if drawing.name == file]
485
                if not drawing or not drawing[0].UID:
486
                    drawings.append(Drawing(None, file, None))
482
                x = [drawing for drawing in drawings if drawing.name == file]
483
                if not x or not x[0].UID:
484
                    drawing = Drawing(None, file, None)
485
                    drawings.append(drawing)
486
                else:
487
                    drawing = x[0]
487 488

  
488
                item = QTreeWidgetItem(self.treeWidgetDrawingList.root,
489
                                       [file, drawing[0].datetime if drawing else None])
489
                item = QTreeWidgetItem(self.treeWidgetDrawingList.root, [file, drawing.datetime])
490 490
                item.setIcon(0, QIcon(':newPrefix/image.png'))
491 491
                item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
492 492
                item.setCheckState(0, Qt.Unchecked)
493
                item.setData(Qt.UserRole, 0, drawing)
493 494

  
494 495
            self.treeWidgetDrawingList.root.setText(0, self.tr('P&ID Drawings') + '({})'.format(
495 496
                self.treeWidgetDrawingList.root.childCount()))
......
499 500

  
500 501
            app_doc_data.saveDrawings(drawings)
501 502
        except Exception as ex:
502
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
503
                                                          sys.exc_info()[-1].tb_lineno)
503
            message = 'error occurred({}) in {}:{}'.format(repr(ex), sys.exc_info()[-1].tb_frame.f_code.co_filename,
504
                                                           sys.exc_info()[-1].tb_lineno)
504 505
            self.addMessage.emit(MessageType.Error, message)
505 506

  
506 507
    def open_selected_drawing(self, item, column):
507
        """
508
        @brief      open selected p&id drawing
509
        @author     humkyung
510
        @date       18.11.02
511
        """
512
        appDocData = AppDocData.instance()
513
        drawing = os.path.join(appDocData.getCurrentProject().getDrawingFilePath(), item.text(0))
514
        self.onOpenImageDrawing(drawing)
508
        """open selected p&id drawing"""
509

  
510
        app_doc_data = AppDocData.instance()
511
        drawing = item.data(Qt.UserRole, 0)
512
        if drawing:
513
            self.open_image_drawing(drawing)
515 514

  
516 515
    def show_detect_symbol_dialog(self):
517 516
        from DetectSymbolDialog import QDetectSymbolDialog
......
534 533
            dialog.exec_()
535 534
        except Exception as ex:
536 535
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
537
                                                          sys.exc_info()[-1].tb_lineno)
536
                                                           sys.exc_info()[-1].tb_lineno)
538 537
            self.addMessage.emit(MessageType.Error, message)
539 538

  
540 539
        return
......
552 551
            dialog.exec_()
553 552
        except Exception as ex:
554 553
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
555
                                                          sys.exc_info()[-1].tb_lineno)
554
                                                           sys.exc_info()[-1].tb_lineno)
556 555
            self.addMessage.emit(MessageType.Error, message)
557 556

  
558

  
559 557
    def symbolTrainingClicked(self):
560 558
        try:
561 559
            dialog = QTrainingSymbolImageListDialog(self)
562 560
            dialog.exec_()
563 561
        except Exception as ex:
564 562
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
565
                                                          sys.exc_info()[-1].tb_lineno)
563
                                                           sys.exc_info()[-1].tb_lineno)
566 564
            self.addMessage.emit(MessageType.Error, message)
567 565

  
568 566
    '''
......
628 626
                            titleBlockItems.append(item)
629 627

  
630 628
            # unknown item is not saved now for performance
631
            db_items = [item for item in items if issubclass(type(item), QEngineeringAbstractItem) and type(item) is not QGraphicsBoundingBoxItem and type(item) is not QEngineeringErrorItem and type(item) is not QEngineeringLineNoTextItem and type(item) is not QEngineeringUnknownItem]
629
            db_items = [item for item in items if issubclass(type(item), QEngineeringAbstractItem) and type(
630
                item) is not QGraphicsBoundingBoxItem and type(item) is not QEngineeringErrorItem and type(
631
                item) is not QEngineeringLineNoTextItem and type(item) is not QEngineeringUnknownItem]
632 632
            db_items.extend([item for item in items if type(item) is QEngineeringLineNoTextItem])
633 633
            db_items.extend([line for line in appDocData.tracerLineNos if type(line) is QEngineeringTrimLineNoTextItem])
634 634
            db_items.extend(titleBlockItems)
......
647 647
            appDocData.saveToDatabase(db_items)
648 648
        except Exception as ex:
649 649
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
650
                                                          sys.exc_info()[-1].tb_lineno)
650
                                                           sys.exc_info()[-1].tb_lineno)
651 651
            self.addMessage.emit(MessageType.Error, message)
652 652

  
653 653
    def save_drawing_if_necessary(self):
......
711 711
            self._save_work_cmd.start()
712 712
        except Exception as ex:
713 713
            message = 'error occurred({}) in {}:{}'.format(repr(ex), sys.exc_info()[-1].tb_frame.f_code.co_filename,
714
                                                          sys.exc_info()[-1].tb_lineno)
714
                                                           sys.exc_info()[-1].tb_lineno)
715 715
            self.addMessage.emit(MessageType.Error, message)
716 716

  
717 717
    def save_finished(self):
......
759 759
            self.listWidgetLog.insertItem(0, item)
760 760
        except Exception as ex:
761 761
            print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
762
                                                      sys.exc_info()[-1].tb_lineno))
762
                                                       sys.exc_info()[-1].tb_lineno))
763 763

  
764 764
    '''
765 765
        @brief      clear log
......
869 869
            subprocess.call(filePath, shell=False)
870 870
        except Exception as ex:
871 871
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
872
                                                          sys.exc_info()[-1].tb_lineno)
872
                                                           sys.exc_info()[-1].tb_lineno)
873 873
            self.addMessage.emit(MessageType.Error, message)
874 874

  
875 875
    def onImportTextFromCAD(self):
......
881 881
            dialog.exec_()
882 882
        except Exception as ex:
883 883
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
884
                                                          sys.exc_info()[-1].tb_lineno)
884
                                                           sys.exc_info()[-1].tb_lineno)
885 885
            self.addMessage.emit(MessageType.Error, message)
886 886

  
887 887
    def onSymbolThickness(self):
......
892 892
            dialog.exec_()
893 893
        except Exception as ex:
894 894
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
895
                                                          sys.exc_info()[-1].tb_lineno)
895
                                                           sys.exc_info()[-1].tb_lineno)
896 896
            self.addMessage.emit(MessageType.Error, message)
897 897

  
898 898
    def on_help(self):
......
904 904
            os.system('"{}"'.format(help_file_path))
905 905
        except Exception as ex:
906 906
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
907
                                                          sys.exc_info()[-1].tb_lineno)
907
                                                           sys.exc_info()[-1].tb_lineno)
908 908
            self.addMessage.emit(MessageType.Error, message)
909 909

  
910 910
    '''
......
981 981

  
982 982
        except Exception as ex:
983 983
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
984
                                                          sys.exc_info()[-1].tb_lineno)
984
                                                           sys.exc_info()[-1].tb_lineno)
985 985
            self.addMessage.emit(MessageType.Error, message)
986 986

  
987 987
    '''
......
1103 1103
                    QMessageBox.about(self.graphicsView, self.tr("Notice"), self.tr("Fail to recognize text"))
1104 1104
        except Exception as ex:
1105 1105
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1106
                                                          sys.exc_info()[-1].tb_lineno)
1106
                                                           sys.exc_info()[-1].tb_lineno)
1107 1107
            self.addMessage.emit(MessageType.Error, message)
1108 1108

  
1109 1109
    '''
......
1235 1235
            dialog.exec_()
1236 1236
        except Exception as ex:
1237 1237
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1238
                                                          sys.exc_info()[-1].tb_lineno)
1238
                                                           sys.exc_info()[-1].tb_lineno)
1239 1239
            self.addMessage.emit(MessageType.Error, message)
1240 1240

  
1241 1241
    '''
......
1282 1282
                    humkyung 2018.08.22 clear scene before loading xml file
1283 1283
    '''
1284 1284

  
1285
    def onOpenImageDrawing(self, path=None):
1285
    def open_image_drawing(self, drawing):
1286 1286
        from Drawing import Drawing
1287 1287

  
1288 1288
        try:
......
1291 1291
                self._save_work_cmd.wait()
1292 1292

  
1293 1293
            app_doc_data = AppDocData.instance()
1294

  
1295 1294
            project = app_doc_data.getCurrentProject()
1296 1295

  
1297
            self.path = self.graphicsView.loadImageFromFile(project.getDrawingFilePath(),
1298
                                                            path if type(path) is str else '')
1296
            self.path = self.graphicsView.loadImageFromFile(drawing)
1299 1297
            if os.path.isfile(self.path):
1300 1298
                self.onCommandRejected()
1301 1299
                app_doc_data.clear()
1302 1300

  
1303 1301
                app_doc_data.setImgFilePath(self.path)
1304
                app_doc_data.activeDrawing = Drawing(None, app_doc_data.imgName, None)
1302
                app_doc_data.activeDrawing = drawing
1305 1303
                if not app_doc_data.set_occupying_drawing(app_doc_data.activeDrawing.UID):
1306 1304
                    QMessageBox.about(self.graphicsView, self.tr("Notice"),
1307 1305
                                      self.tr("The drawing is locked for editing by another user"))
......
1703 1701
                             type(text) is QEngineeringTextItem]
1704 1702
                if not textItems or len(textItems) is 1:
1705 1703
                    return
1706
                
1704

  
1707 1705
                angle = None
1708 1706
                for item in textItems:
1709 1707
                    if angle is None:
......
1713 1711
                            return
1714 1712

  
1715 1713
                textItems = sorted(textItems, key=lambda text: text.loc[1]) if textItems[0].angle == 0 else ( \
1716
                                sorted(textItems, key=lambda text: text.loc[0]) if textItems[0].angle == 1.57 else ( \
1717
                                    sorted(textItems, key=lambda text: text.loc[1], reverse=True) if textItems[0].angle == 4.71 else \
1718
                                        sorted(textItems, key=lambda text: text.loc[0], reverse=True)))
1714
                    sorted(textItems, key=lambda text: text.loc[0]) if textItems[0].angle == 1.57 else ( \
1715
                        sorted(textItems, key=lambda text: text.loc[1], reverse=True) if textItems[0].angle == 4.71 else \
1716
                            sorted(textItems, key=lambda text: text.loc[0], reverse=True)))
1719 1717
                minX = sys.maxsize
1720 1718
                minY = sys.maxsize
1721 1719
                maxX = 0
......
1749 1747
            QMainWindow.keyPressEvent(self, event)
1750 1748
        except Exception as ex:
1751 1749
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1752
                                                          sys.exc_info()[-1].tb_lineno)
1750
                                                           sys.exc_info()[-1].tb_lineno)
1753 1751
            self.addMessage.emit(MessageType.Error, message)
1754 1752

  
1755 1753
    def recognizeBatch(self, MainWindow):
......
1762 1760
        from datetime import datetime
1763 1761
        from RecognitionDialog import QRecognitionDialog
1764 1762

  
1765
        appDocData = AppDocData.instance()
1766
        project = appDocData.getCurrentProject()
1767
        appDocData.needReOpening = None
1768
        currentPid = None
1763
        app_doc_data = AppDocData.instance()
1764
        project = app_doc_data.getCurrentProject()
1765
        app_doc_data.needReOpening = None
1766
        current_drawing, currentPid = None, None
1769 1767

  
1770 1768
        if self.graphicsView.hasImage():
1771
            currentPid = appDocData.activeDrawing.name
1769
            current_drawing = app_doc_data.activeDrawing
1770
            currentPid = app_doc_data.activeDrawing.name
1772 1771

  
1772
        # TODO: 무슨 의미인지 주석 필요
1773 1773
        drawingTop = self.treeWidgetDrawingList.topLevelItem(0)
1774 1774
        drawingCount = drawingTop.childCount()
1775 1775
        checkedTreeItems = []
......
1780 1780
                checkedTreeItems.append(drawingChild)
1781 1781
                checkedDrawingPath.append(os.path.join(project.getDrawingFilePath(), drawingChild.data(0, 0)))
1782 1782
                if currentPid is not None and drawingChild.data(0, 0).find(currentPid) is 0:
1783
                    appDocData.needReOpening = False  # later check need reopening at drawUnknownItems()
1783
                    app_doc_data.needReOpening = False  # later check need reopening at drawUnknownItems()
1784 1784
                    currentPid = drawingChild.data(0, 0)
1785
        # up to here
1785 1786

  
1786 1787
        if len(checkedDrawingPath) == 0:
1787 1788
            self.showImageSelectionMessageBox()
......
1794 1795
            if self.dlg.isAccepted == True:
1795 1796
                pass
1796 1797

  
1797
            if appDocData.needReOpening == True:
1798
                drawing = os.path.join(appDocData.getCurrentProject().getDrawingFilePath(), currentPid)
1799
                self.onOpenImageDrawing(drawing)
1798
            if app_doc_data.needReOpening == True:
1799
                self.open_image_drawing(current_drawing)
1800 1800

  
1801 1801
            # save working date-time
1802
            drawings = appDocData.getDrawings()
1802
            drawings = app_doc_data.getDrawings()
1803 1803
            checkedDrawings = []
1804 1804
            for checkedTreeItem in checkedTreeItems:
1805 1805
                for drawing in drawings:
......
1808 1808
                            drawing.datetime = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
1809 1809
                            checkedDrawings.append(drawing)
1810 1810
                            checkedTreeItem.setText(1, datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
1811
            appDocData.saveDrawings(checkedDrawings)
1811
            app_doc_data.saveDrawings(checkedDrawings)
1812 1812
            self.changeViewCheckedState(True)
1813 1813
            # up to here
1814 1814
        except Exception as ex:
1815
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1816
                                                          sys.exc_info()[-1].tb_lineno)
1815
            message = 'error occurred({}) in {}:{}'.format(repr(ex), sys.exc_info()[-1].tb_frame.f_code.co_filename,
1816
                                                           sys.exc_info()[-1].tb_lineno)
1817 1817
            self.addMessage.emit(MessageType.Error, message)
1818 1818

  
1819 1819
    '''
......
1870 1870
                # up to here
1871 1871
        except Exception as ex:
1872 1872
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1873
                                                          sys.exc_info()[-1].tb_lineno)
1873
                                                           sys.exc_info()[-1].tb_lineno)
1874 1874
            self.addMessage.emit(MessageType.Error, message)
1875 1875

  
1876 1876
    '''
......
1897 1897
            #    _item.remove_assoc_item(item)
1898 1898

  
1899 1899
            matches = [_item for _item in self.graphicsView.scene.items() if type(_item) is QEngineeringLineNoTextItem]
1900
            matches.extend([lineNo for lineNo in AppDocData.instance().tracerLineNos if type(lineNo) is QEngineeringTrimLineNoTextItem])
1900
            matches.extend([lineNo for lineNo in AppDocData.instance().tracerLineNos if
1901
                            type(lineNo) is QEngineeringTrimLineNoTextItem])
1901 1902
            for match in matches:
1902 1903
                if item is match.prop('From'):
1903 1904
                    match.set_property('From', None)
......
1941 1942
            if item.scene() is not None: item.scene().removeItem(item)
1942 1943
        except Exception as ex:
1943 1944
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1944
                                                          sys.exc_info()[-1].tb_lineno)
1945
                                                           sys.exc_info()[-1].tb_lineno)
1945 1946
            self.addMessage.emit(MessageType.Error, message)
1946 1947

  
1947 1948
    '''
......
1987 1988
                self.graphicsView.invalidateScene()
1988 1989
        except Exception as ex:
1989 1990
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1990
                                                          sys.exc_info()[-1].tb_lineno)
1991
                                                           sys.exc_info()[-1].tb_lineno)
1991 1992
            self.addMessage.emit(MessageType.Error, message)
1992 1993

  
1993 1994
    '''
......
2025 2026
            # self.graphicsView.scene.update(self.graphicsView.sceneRect())
2026 2027
        except Exception as ex:
2027 2028
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
2028
                                                          sys.exc_info()[-1].tb_lineno)
2029
                                                           sys.exc_info()[-1].tb_lineno)
2029 2030
            self.addMessage.emit(MessageType.Error, message)
2030 2031

  
2031 2032
    def drawDetectedItemsToScene(self):
......
2139 2140
                    appDocData.allItems.append(item)
2140 2141
        except Exception as ex:
2141 2142
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
2142
                                                          sys.exc_info()[-1].tb_lineno)
2143
                                                           sys.exc_info()[-1].tb_lineno)
2143 2144
            self.addMessage.emit(MessageType.Error, message)
2144 2145

  
2145 2146
    '''
......
2242 2243
            # up to here
2243 2244
        except Exception as ex:
2244 2245
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
2245
                                                          sys.exc_info()[-1].tb_lineno)
2246
                                                           sys.exc_info()[-1].tb_lineno)
2246 2247
            self.addMessage.emit(MessageType.Error, message)
2247 2248

  
2248 2249
    '''
......
2282 2283
                    appDocData.allItems.append(item)
2283 2284
        except Exception as ex:
2284 2285
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
2285
                                                          sys.exc_info()[-1].tb_lineno)
2286
                                                           sys.exc_info()[-1].tb_lineno)
2286 2287
            self.addMessage.emit(MessageType.Error, message)
2287 2288

  
2288 2289
    '''
......
2321 2322
                    appDocData.allItems.append(item)
2322 2323
        except Exception as ex:
2323 2324
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
2324
                                                          sys.exc_info()[-1].tb_lineno)
2325
                                                           sys.exc_info()[-1].tb_lineno)
2325 2326
            self.addMessage.emit(MessageType.Error, message)
2326 2327

  
2327 2328
    '''
......
2431 2432
            SaveWorkCommand.save_to_xml()
2432 2433
        except Exception as ex:
2433 2434
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
2434
                                                          sys.exc_info()[-1].tb_lineno)
2435
                                                           sys.exc_info()[-1].tb_lineno)
2435 2436
            self.addMessage.emit(MessageType.Error, message)
2436 2437

  
2437 2438
    def determineRemainObject(self, idx, contours, imgNot):
......
2807 2808

  
2808 2809
        except Exception as ex:
2809 2810
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
2810
                                                          sys.exc_info()[-1].tb_lineno)
2811
                                                           sys.exc_info()[-1].tb_lineno)
2811 2812
            self.addMessage.emit(MessageType.Error, message)
2812 2813
        finally:
2813 2814
            app_doc_data.clearTempDBData()
......
3046 3047

  
3047 3048
        except Exception as ex:
3048 3049
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
3049
                                                          sys.exc_info()[-1].tb_lineno)
3050
                                                           sys.exc_info()[-1].tb_lineno)
3050 3051
            self.addMessage.emit(MessageType.Error, message)
3051 3052
        finally:
3052 3053
            self.itemTreeWidget.update_item_count()
......
3131 3132
            cv2.imwrite(os.path.join(project.getTempPath(), 'OUTPUT.png'), appDocData.imgOutput)
3132 3133
        except Exception as ex:
3133 3134
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
3134
                                                          sys.exc_info()[-1].tb_lineno)
3135
                                                           sys.exc_info()[-1].tb_lineno)
3135 3136
            self.addMessage.emit(MessageType.Error, message)
3136 3137

  
3137 3138
    '''
......
3260 3261
                sys.exit(app.exec_())
3261 3262
    except Exception as ex:
3262 3263
        print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
3263
                                                  sys.exc_info()[-1].tb_lineno))
3264
                                                   sys.exc_info()[-1].tb_lineno))
3264 3265
    finally:
3265 3266
        pass
DTI_PID/DTI_PID/QtImageViewer.py
194 194
        @date
195 195
    '''
196 196

  
197
    def loadImageFromFile(self, folder='', fileName=""):
197
    def loadImageFromFile(self, drawing):
198 198
        import cv2
199 199
        import numpy as np
200 200
        from AppDocData import AppDocData
......
202 202
        Without any arguments, loadImageFromFile() will popup a file dialog to choose the image file.
203 203
        With a fileName argument, loadImageFromFile(fileName) will attempt to load the specified image file directly.
204 204
        """
205

  
206
        file_path = None
205 207
        try:
206
            if len(fileName) == 0:
208
            app_doc_data = AppDocData.instance()
209

  
210
            cvImg = None
211
            if drawing:
212
                file_path = drawing.file_path
213
                cvImg = drawing.image
214
            else:
207 215
                options = QFileDialog.Options()
208 216
                options |= QFileDialog.DontUseNativeDialog
209 217
                if QT_VERSION_STR[0] == '4':
210
                    fileName = QFileDialog.getOpenFileName(self, "Open image file",
211
                                                           os.getcwd() if folder == '' else folder,
218
                    file_path = QFileDialog.getOpenFileName(self, "Open image file",
219
                                                            app_doc_data.project.getDrawingFilePath(),
212 220
                                                           "Image files(*.png *.jpg)", options=options)
213 221
                elif QT_VERSION_STR[0] == '5':
214
                    fileName, dummy = QFileDialog.getOpenFileName(self, "Open image file",
215
                                                                  os.getcwd() if folder == '' else folder,
222
                    file_path, _ = QFileDialog.getOpenFileName(self, "Open image file",
223
                                                               app_doc_data.project.getDrawingFilePath(),
216 224
                                                                  "Image files(*.png *.jpg)", options=options)
217
            if len(fileName) and os.path.isfile(fileName):
218
                cvImg = cv2.cvtColor(AppDocData.my_imread(fileName), cv2.COLOR_BGR2GRAY)
219
                # blur = cv2.GaussianBlur(cvImg, (5,5),0)
225

  
226
                _bytes = None
227
                with open(file_path.encode('utf-8'), 'rb') as stream:
228
                    _bytes = stream.read()
229

  
230
                numpyArray = np.asarray(bytearray(_bytes), dtype=np.uint8)
231
                image = cv2.imdecode(numpyArray, cv2.IMREAD_UNCHANGED)
232
                cvImg = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
220 233
                cvImg = cv2.threshold(cvImg, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
221 234

  
222
                # skeletonize
223
                '''
224
                from skimage import io
225
                from skimage import morphology
226

  
227
                image = io.imread(fileName)
228
                out = morphology.skeletonize(image > 0)
229
                io.imshow(out)
230
                cvImg = out[:, :, ::-1]
231
                cv2.namedWindow('original', cv2.WINDOW_NORMAL)
232
                cv2.imshow('original',cvImg)
233
                '''
234
                '''
235
                cvImg = ~cvImg
236
                
237
                size = np.size(cvImg)
238
                skel = np.zeros(cvImg.shape,np.uint8)
239

  
240
                element = cv2.getStructuringElement(cv2.MORPH_CROSS,(3,3))
241
                done = False
242
 
243
                while( not done):
244
                    eroded = cv2.erode(cvImg,element)
245
                    temp = cv2.dilate(eroded,element)
246
                    temp = cv2.subtract(cvImg,temp)
247
                    skel = cv2.bitwise_or(skel,temp)
248
                    cvImg = eroded.copy()
249
 
250
                    zeros = size - cv2.countNonZero(cvImg)
251
                    if zeros==size:
252
                        done = True
253
                cvImg = ~skel
254
                '''
255

  
256
                configs = AppDocData.instance().getConfigs('Filter', 'DilateSize')
235
                configs = app_doc_data.getConfigs('Filter', 'DilateSize')
257 236
                if 1 == len(configs) and int(configs[0].value) is not 0:
258 237
                    size = int(configs[0].value)
259 238
                    kernel = np.ones((size, size), np.uint8)
260 239
                    cvImg = cv2.erode(cvImg, kernel, iterations=1)
261 240

  
262
                configs = AppDocData.instance().getConfigs('Filter', 'FlatSize')
241
                configs = app_doc_data.getConfigs('Filter', 'FlatSize')
263 242
                if 1 == len(configs) and int(configs[0].value) is not 0:
264 243
                    size = int(configs[0].value)
265 244
                    kernel = np.ones((size, size), np.uint8)
266 245
                    cvImg = cv2.morphologyEx(cvImg, cv2.MORPH_CLOSE, kernel)
267 246
                    cvImg = cv2.morphologyEx(cvImg, cv2.MORPH_OPEN, kernel)
268 247

  
269
                bytesPerLine = cvImg.shape[1]
270
                image = QImage(cvImg.data, cvImg.shape[1], cvImg.shape[0], bytesPerLine, QImage.Format_Indexed8)
271
                self.setImage(image)
248
            bytesPerLine = cvImg.shape[1]
249
            image = QImage(cvImg.data, cvImg.shape[1], cvImg.shape[0], bytesPerLine, QImage.Format_Indexed8)
250
            self.setImage(image)
272 251
        except Exception as ex:
273
            print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
274
                                                       sys.exc_info()[-1].tb_lineno))
252
            from App import App
253
            from AppDocData import MessageType
254

  
255
            message = 'error occurred({}) in {}:{}'.format(repr(ex), sys.exc_info()[-1].tb_frame.f_code.co_filename,
256
                                                           sys.exc_info()[-1].tb_lineno)
257
            App.mainWnd().addMessage.emit(MessageType.Error, message)
275 258

  
276
        return fileName
259
        return file_path
277 260

  
278 261
    '''
279 262
        @history    2018.06.27  Jeongwoo    Change zoom rule (Qt.KeepAspectRatioByExpanding → Qt.KeepAspectRatio)

내보내기 Unified diff

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