Exemple #1
0
    def openFiles(self):
        # Open files import dialog
        self.openFilesDialog = myOpenFilesDialog(self)

        # If both files are imported, start process the image
        if self.openFilesDialog.exec_() == 10:
            # Clear the previous data and reset the program
            self._DrawingContour = False
            self.MainUI.graphicsView.setCursor(Qt.ArrowCursor)
            self.paintingScene.clear()
            self._ContourRedraw = None
            self.scene.clear()
            self.MainUI.graphicsView.setScene(self.scene)
            self.removeWorkingFiles()
            self._DrawingRatio = 1

            #
            # Pre-process the image and display it
            self.MainUI.statusbar.showMessage('Processing...')
            cv2.waitKey(1)
            self._MainImage = cv2.imread(self._PhotoDir)

            #
            # Undistort the image
            try:
                self.MainUI.statusbar.showMessage('Un-distorting...')
                cv2.waitKey(1)
                self._MainImage = undistortImage(self._MainImage,
                                                 self._CamMatrixDir)
                self.MainUI.progressBar.setValue(10)
            except Exception as e:
                print('Error:', e)
                QMessageBox.warning(
                    self,
                    'Error undistort image',
                    'Error when undistort the image.\nImport correct '
                    'Camera Matrix.',
                    buttons=QMessageBox.Ok)
                self.MainUI.statusbar.showMessage('Ready')
                self.MainUI.progressBar.setValue(0)
                return

            #
            # Perspective transform
            try:
                self.MainUI.statusbar.showMessage(
                    'Perspective transforming...')
                cv2.waitKey(1)
                # Find the chessboard corners
                corners = findChessboardInImage(self._MainImage,
                                                Width=6,
                                                Height=9)

                if len(corners) == 0:
                    raise ValueError('No corner found!')

                # Get the points for perspective transform
                oldChessBoardCorners = getChessboardCorners(corners)
                self._ChessBoardCorners = getNewPoints(Width=6,
                                                       Height=9,
                                                       Size=(8000, 8000))

                # Transform, crop black border and save the image
                self._MainImage = cropImgPerspectively(self._MainImage,
                                                       oldChessBoardCorners,
                                                       self._ChessBoardCorners)
                self._MainImage = cropBlackBorder(self._MainImage)
                self._MainImageDir = self._PhotoDir.split('/')[-1].split(
                    '.')[0] + '_after.jpg'
                cv2.imwrite(self._MainImageDir, self._MainImage)
                self._CurrentFileDir = self._MainImageDir
                self.MainUI.progressBar.setValue(25)

                # Display image
                w, h = self.MainUI.graphicsView.width(
                ), self.MainUI.graphicsView.height()
                image = QtGui.QPixmap(self._CurrentFileDir).scaled(
                    w, h, Qt.KeepAspectRatio)
                item = QGraphicsPixmapItem(image)
                self.scene.addItem(item)
            except Exception as e:
                print('Error:', e)
                QMessageBox.warning(
                    self,
                    'Error finding chessboard',
                    'Error when finding chessboard the '
                    'image.\nImport image contains a chessboard.',
                    buttons=QMessageBox.Ok)
                self.MainUI.statusbar.showMessage('Ready')
                self.MainUI.progressBar.setValue(0)
                return

            #
            # Trace the possible contour
            try:
                self.MainUI.statusbar.showMessage('Finding contour...')
                cv2.waitKey(1)
                # Find edges and filter our 1 possible contour
                imageWithEdges, possibleContour = findContours(
                    self._MainImage,
                    Hull=False,
                    MinArcLength=1000,
                    Background=False)
                self.MainUI.progressBar.setValue(50)

                # Trace the possible contour
                self.MainUI.statusbar.showMessage('Tracing contour...')
                cv2.waitKey(1)
                imageWithEdges = cv2.cvtColor(imageWithEdges,
                                              cv2.COLOR_BGR2GRAY)
                ret, imageWithEdges = cv2.threshold(imageWithEdges, 127, 255,
                                                    cv2.THRESH_BINARY)
                startingPoint = (possibleContour[0][0][1],
                                 possibleContour[0][0][0])
                self._MainContour, closedLoop = traceTheContour(
                    imageWithEdges, startingPoint)
                self.MainUI.progressBar.setValue(75)

                # Draw the contour over the image
                self.MainUI.statusbar.showMessage('Drawing contour...')
                cv2.waitKey(1)
                size = imageWithEdges.shape[:2]
                imageWithContour = drawTheContour(size,
                                                  self._MainContour,
                                                  Background=self._MainImage,
                                                  CloseLoop=closedLoop)

                # Save the image
                self._ImageWithContourDir = self._MainImageDir.split(
                    '/')[-1].split('.')[0] + '_withContour.jpg'
                cv2.imwrite(self._ImageWithContourDir, imageWithContour)
                self._CurrentFileDir = self._ImageWithContourDir

                # Enable 'Calculate' button if closed loop found
                if not closedLoop:
                    QMessageBox.warning(
                        self,
                        'No closed loop found',
                        'No closed loop contour found in the '
                        'image.\nTry drawing the contour manually.',
                        buttons=QMessageBox.Ok)
                else:
                    self.MainUI.calculateButton.setEnabled(True)
            except Exception as e:
                print('Error:', e)
                QMessageBox.warning(
                    self,
                    'Error finding contour',
                    'Error when finding contour in the '
                    'image.\nTry drawing the contour manually.',
                    buttons=QMessageBox.Ok)
                self.MainUI.statusbar.showMessage('Ready')
                self.MainUI.progressBar.setValue(0)

            #
            # Display image
            w, h = self.MainUI.graphicsView.width(
            ), self.MainUI.graphicsView.height()
            image = QtGui.QPixmap(self._CurrentFileDir).scaled(
                w, h, Qt.KeepAspectRatio)
            item = QGraphicsPixmapItem(image)
            self.scene.addItem(item)

            self.MainUI.progressBar.setValue(100)

            # Enable buttons
            self.MainUI.cancelButton.setEnabled(True)
            self.MainUI.redrawButton.setEnabled(True)
            self.MainUI.statusbar.showMessage('Ready')
Exemple #2
0
    def openFiles(self):
        # Open files import dialog
        self.openFilesDialog = myOpenFilesDialog(self)

        openFilesResult = self.openFilesDialog.exec_()
        # If at least one file is imported, start process the image
        if openFilesResult == 10 or openFilesResult == 5:
            # Clear the previous data and reset the program
            self._DrawingContour = False
            self.MainUI.graphicsView.setCursor(Qt.ArrowCursor)
            self.paintingScene.clear()
            self._ContourRedraw = None
            self.scene.clear()
            self.MainUI.graphicsView.setScene(self.scene)
            self.removeWorkingFiles()
            self._DrawingRatio = 1

            # Display image
            w, h = self.MainUI.graphicsView.width(
            ), self.MainUI.graphicsView.height()
            image = QtGui.QPixmap(self._PhotoDir).scaled(
                w, h, Qt.KeepAspectRatio)
            item = QGraphicsPixmapItem(image)
            self.scene.clear()
            self.scene.addItem(item)
            cv2.waitKey(1)

            #
            # Pre-process the image and display it
            self.MainUI.statusbar.showMessage('Processing...')
            cv2.waitKey(1)
            self._MainImage = cv2.imread(self._PhotoDir)

            #
            # Undistort the image if a camera matrix is imported
            if openFilesResult == 10:
                try:
                    self.MainUI.statusbar.showMessage('Un-distorting...')
                    cv2.waitKey(1)
                    self._MainImage = undistortImage(self._MainImage,
                                                     self._CamMatrixDir)
                    self.MainUI.progressBar.setValue(10)
                    print('Undistort completed')
                except Exception as e:
                    print('Error:', e)
                    QMessageBox.warning(
                        self,
                        'Error undistort image',
                        'Error when undistort the image.\nImport '
                        'correct Camera Matrix.',
                        buttons=QMessageBox.Ok)
                    self.MainUI.statusbar.showMessage('Ready')
                    self.MainUI.progressBar.setValue(0)
                    return

            #
            # Perspective transform
            try:
                self.MainUI.statusbar.showMessage(
                    'Perspective transforming...')
                cv2.waitKey(1)
                # Find the chessboard corners
                showImg('main', self._MainImage, 1280)
                cv2.waitKey(0)
                cv2.destroyWindow('main')
                corners = findChessboardInImage(self._MainImage,
                                                Width=6,
                                                Height=9)

                if len(corners) == 0:
                    raise ValueError('No corner found!')

                # Get the points for perspective transform
                oldChessBoardCorners = getChessboardCorners(corners)
                # Find the orientation of the chessboard
                Dx = oldChessBoardCorners[1][0] - oldChessBoardCorners[0][0]
                Dy = oldChessBoardCorners[1][1] - oldChessBoardCorners[0][1]
                if Dx == 0:
                    chessboardDirection = 100
                else:
                    chessboardDirection = abs(Dy / Dx)
                backgroundSize = (15000, 15000)
                if chessboardDirection < 1:
                    self._ChessBoardCorners = getNewPoints(Width=6,
                                                           Height=9,
                                                           Size=backgroundSize,
                                                           Direction=1)
                else:
                    self._ChessBoardCorners = getNewPoints(Width=6,
                                                           Height=9,
                                                           Size=backgroundSize,
                                                           Direction=2)

                # Transform, crop black border and save the image
                self._MainImage = cropImgPerspectively(self._MainImage,
                                                       oldChessBoardCorners,
                                                       self._ChessBoardCorners,
                                                       Size=backgroundSize)
                showImg('after transform', self._MainImage, 800)
                cv2.waitKey(0)
                cv2.destroyWindow('after transform')
                self._MainImage = cropBlackBorder(self._MainImage)
                self._MainImage = reduceImgSize(self._MainImage, 4000)
                showImg('after cropBlackBorder', self._MainImage, 800)
                cv2.waitKey(0)
                cv2.destroyWindow('after cropBlackBorder')
                self._MainImageDir = self._PhotoDir.split('/')[-1].split(
                    '.')[0] + '_after.jpg'
                cv2.imwrite(self._MainImageDir, self._MainImage)
                self._CurrentFileDir = self._MainImageDir
                self.MainUI.progressBar.setValue(25)
                print('Perspective transform completed')

                # Display image
                w, h = self.MainUI.graphicsView.width(
                ), self.MainUI.graphicsView.height()
                image = QtGui.QPixmap(self._CurrentFileDir).scaled(
                    w, h, Qt.KeepAspectRatio)
                item = QGraphicsPixmapItem(image)
                self.scene.clear()
                self.scene.addItem(item)
                cv2.waitKey(1)
            except Exception as e:
                print('Error:', e)
                QMessageBox.warning(
                    self,
                    'Error finding chessboard',
                    'Error when finding chessboard the '
                    'image.\nImport image contains a chessboard.',
                    buttons=QMessageBox.Ok)
                self.MainUI.statusbar.showMessage('Ready')
                self.MainUI.progressBar.setValue(0)
                return

            #
            # Trace the possible contour
            try:
                self.MainUI.statusbar.showMessage('Finding contour...')
                cv2.waitKey(1)

                # Find edges and filter our 1 possible contour
                imageWithEdges, possibleContour = findContours(
                    self._MainImage,
                    Hull=False,
                    MinArcLength=1000,
                    Background=False,
                    ChessboardDirection=chessboardDirection)
                self.MainUI.progressBar.setValue(50)

                showImg('imageWithEdge', imageWithEdges, 800)
                cv2.waitKey(0)

                closedLoop = False
                size = imageWithEdges.shape[:2]
                try:
                    # Trace the possible contour
                    # raise Exception('my error')
                    self.MainUI.statusbar.showMessage('Tracing contour...')
                    cv2.waitKey(1)
                    imageWithEdges = cv2.cvtColor(imageWithEdges,
                                                  cv2.COLOR_BGR2GRAY)
                    ret, imageWithEdges = cv2.threshold(
                        imageWithEdges, 50, 255, cv2.THRESH_BINARY)
                    startingPoint = (possibleContour[0][0][1],
                                     possibleContour[0][0][0])
                    showImg('imageWithEdge', imageWithEdges, 800)
                    cv2.waitKey(0)
                    self._MainContour, closedLoop = traceTheContour(
                        imageWithEdges, startingPoint)
                    self.MainUI.progressBar.setValue(75)
                    print('Contour length before fitting:',
                          len(self._MainContour))

                    try:
                        # Perform curve fitting
                        # raise Exception('my error')
                        self._MainContour = contourFitting(self._MainContour,
                                                           size,
                                                           Order=5)
                        print('Contour length after fitting: ',
                              len(self._MainContour))
                        # End curve fitting
                    except Exception as e:
                        print('Error:', e)
                        print(
                            'Failed to fit the contour, original contour will be used.'
                        )

                except Exception as e:
                    print('Error:', e)
                    print(
                        'Failed to trace the contour, raw data will be used.')
                    self._MainContour = np.hstack(
                        (possibleContour[:, :, 1], possibleContour[:, :, 0]))

                # Draw the contour over the image
                self.MainUI.statusbar.showMessage('Drawing contour...')
                cv2.waitKey(1)
                imageWithContour = drawTheContour(
                    size,
                    self._MainContour.astype(int),
                    LineThickness=3,
                    Background=self._MainImage,
                    CloseLoop=closedLoop)

                # Save the image
                self._ImageWithContourDir = self._MainImageDir.split(
                    '/')[-1].split('.')[0] + '_withContour.jpg'
                cv2.imwrite(self._ImageWithContourDir, imageWithContour)
                self._CurrentFileDir = self._ImageWithContourDir
                '''# Enable 'Calculate' button if closed loop found
                if not closedLoop:
                    QMessageBox.warning(self, 'No closed loop found', 'No closed loop contour found in the '
                                                                      'image.\nTry drawing the contour manually.',
                                        buttons=QMessageBox.Ok)
                else:
                    self.MainUI.calculateButton.setEnabled(True)'''

                # Enable 'Calculate' button
                self.MainUI.calculateButton.setEnabled(True)
            except Exception as e:
                print('Error:', e)
                QMessageBox.warning(
                    self,
                    'Error finding contour',
                    'Error when finding contour in the '
                    'image.\nTry drawing the contour manually.',
                    buttons=QMessageBox.Ok)
                self.MainUI.redrawButton.setEnabled(True)
                self.MainUI.statusbar.showMessage('Ready')
                self.MainUI.progressBar.setValue(100)

            #
            # Display image
            w, h = self.MainUI.graphicsView.width(
            ), self.MainUI.graphicsView.height()
            image = QtGui.QPixmap(self._CurrentFileDir).scaled(
                w, h, Qt.KeepAspectRatio)
            item = QGraphicsPixmapItem(image)
            self.scene.clear()
            self.scene.addItem(item)

            self.MainUI.progressBar.setValue(100)

            # Enable buttons
            self.MainUI.cancelButton.setEnabled(True)
            self.MainUI.redrawButton.setEnabled(True)
            self.MainUI.statusbar.showMessage('Ready')
            cv2.waitKey(1)

        elif openFilesResult == 0:
            return
        else:
            print(openFilesResult)
            QMessageBox.warning(
                self,
                'Error importing',
                'Error when importing camera matrix or photo.\nTry to import '
                'again.',
                buttons=QMessageBox.Ok)
    def postProcessing(self):
        # Set button
        self.MainUI.redrawButton.setEnabled(False)
        self.MainUI.redrawButton.setText('Re-draw')

        #
        # Trace the possible contour
        try:
            self.MainUI.statusbar.showMessage('Finding contour...')
            cv2.waitKey(1)

            # Manual Section mode
            if self._SelectionMode == 2:
                # Find edges and filter our 1 possible contour
                imageWithEdges, possibleContour = findContours(
                    self._MainImage,
                    GrabCutMask=self._GrabCutResult,
                    Hull=False,
                    MinArcLength=1000,
                    Background=False,
                    ChessboardDirection=self._ChessboardDirection)

            # Auto selection mode
            else:
                # Find edges and filter our 1 possible contour
                imageWithEdges, possibleContour = findContours(
                    self._MainImage,
                    Hull=False,
                    MinArcLength=1000,
                    Background=False,
                    ChessboardDirection=self._ChessboardDirection)

            self.MainUI.progressBar.setValue(50)

            showImg('imageWithEdge', imageWithEdges, 800)
            cv2.waitKey(0)

            closedLoop = False
            size = imageWithEdges.shape[:2]
            try:
                # Trace the possible contour
                self.MainUI.statusbar.showMessage('Tracing contour...')
                cv2.waitKey(1)
                imageWithEdges = cv2.cvtColor(imageWithEdges,
                                              cv2.COLOR_BGR2GRAY)
                ret, imageWithEdges = cv2.threshold(imageWithEdges, 50, 255,
                                                    cv2.THRESH_BINARY)
                startingPoint = (possibleContour[0][0][1],
                                 possibleContour[0][0][0])
                showImg('imageWithEdge', imageWithEdges, 800)
                cv2.waitKey(0)
                self._MainContour, closedLoop = traceTheContour(
                    imageWithEdges, startingPoint)
                self.MainUI.progressBar.setValue(75)
                print('Contour length after tracing:', len(self._MainContour))

                if self._CurveFitting:
                    try:
                        # Perform curve fitting
                        self._MainContour = contourFitting(self._MainContour,
                                                           size,
                                                           Order=5)
                        print('Contour length after fitting: ',
                              len(self._MainContour))
                        # End curve fitting
                    except Exception as e:
                        print('Error:', e)
                        print(
                            'Failed to fit the contour, original contour will be used.'
                        )

            except Exception as e:
                print('Error:', e)
                print('Failed to trace the contour, raw data will be used.')
                self._MainContour = np.hstack(
                    (possibleContour[:, :, 1], possibleContour[:, :, 0]))

            # Draw the contour over the image
            self.MainUI.statusbar.showMessage('Drawing contour...')
            cv2.waitKey(1)
            imageWithContour = drawTheContour(size,
                                              self._MainContour.astype(int),
                                              LineThickness=3,
                                              Background=self._MainImage,
                                              CloseLoop=closedLoop)

            # Save the image
            self._ImageWithContourDir = self._MainImageDir.split(
                '/')[-1].split('.')[0] + '_withContour.jpg'
            cv2.imwrite(self._ImageWithContourDir, imageWithContour)
            self._CurrentFileDir = self._ImageWithContourDir

            # Enable 'Calculate' button
            self.MainUI.calculateButton.setEnabled(True)
        except Exception as e:
            print('Error:', e)
            QMessageBox.warning(self,
                                'Error finding contour',
                                'Error when finding contour in the '
                                'image.\nTry drawing the contour manually.',
                                buttons=QMessageBox.Ok)
            self.MainUI.redrawButton.setEnabled(True)
            self.MainUI.statusbar.showMessage('Ready')
            self.MainUI.progressBar.setValue(100)

        #
        # Display image
        w, h = self.MainUI.graphicsView.width(
        ), self.MainUI.graphicsView.height()
        image = QtGui.QPixmap(self._CurrentFileDir).scaled(
            w, h, Qt.KeepAspectRatio)
        item = QGraphicsPixmapItem(image)
        self.scene.clear()
        self.MainUI.graphicsView.setScene(self.scene)
        self.scene.addItem(item)

        self.MainUI.progressBar.setValue(100)

        # Enable buttons
        self.MainUI.cancelButton.setEnabled(True)
        self.MainUI.redrawButton.setEnabled(True)
        self.MainUI.statusbar.showMessage('Ready')
        cv2.waitKey(1)