Exemple #1
0
    def saveProject(self):
        if self.project.empty:
            return

        savePath = self.project.projectPath
        if not savePath:
            savePath, _ = QFileDialog.getSaveFileName(
                self,
                values.saveProjectDialogTitle,
                self.appSettings.lastProjectPath,
                f'{values.appName} files (*{PROJECT_FILE_EXT})',
                options=QFileDialog.DontUseNativeDialog)
            if savePath:
                _, ext = os.path.splitext(savePath)
                if ext != PROJECT_FILE_EXT:
                    savePath += PROJECT_FILE_EXT
                self.project.projectPath = savePath

        if savePath:
            try:
                self.project.save()
                self.appSettings.lastProjectPath = savePath
                self.setCurrentProject()
            except Exception as err:
                logger.error(err)
                self.ui.errorMsg(values.saveProjectErrorMessage)
Exemple #2
0
    def read(self):
        if utils.fileExists(self.filePath):
            self.image: np.ndarray = cv.imread(self.filePath, flags=self.flags)
            if self.image is None:
                return

            try:
                with open(utils.swapExt(self.filePath, '.im')) as fp:
                    data: dict = json.load(fp)
                    self.name = data.get('name', self.name)
                    self.position = data.get('position', self.position)
                    self.scale = data.get('scale', self.scale)
                    self.colormap = data.get('colormap', self.colormap)
                    self.maprange = data.get('maprange', self.maprange)
                    self.transform = data.get('transform', self.transform)
                    self.flags = data.get('flags', self.flags)
                    shapesData = data.get('shapes', None)
                    if shapesData is not None:
                        for name, shapeSet in shapesData.items():
                            self.shapes[name] = []
                            for shapeData in shapeSet:
                                shape = Shape()
                                shape.data = shapeData
                                self.shapes[name].append(shape)

            except OSError:
                pass
            except Exception as err:
                logger.error(err)
 def choose(self, app):
     tunnel = None
     try:
         tunnel = [s for s in sockInfo if sockInfo.get(s).type == "client_tunnel" and
                   sockInfo.get(s).status == "unused"][0]
     except IndexError, e:
         logger.error("no enough free tunnel")
         return None
Exemple #4
0
 def loadProjectFile(self, filePath):
     try:
         projectSettings = ProjectSettings.load(filePath)
     except Exception as err:
         logger.error(err)
         self.ui.errorMsg(f'Error loading project {filePath}.')
         self.updateRecentProjectsActions()
     else:
         self.loadProject(projectSettings)
Exemple #5
0
    def saveAppSettings(self):
        self.appSettings.mainWindowPos = self.ui.pos
        self.appSettings.mainWindowSize = self.ui.size

        try:
            self.appSettings.save()
        except Exception as err:
            logger.error(err)
            self.ui.errorMsg('Error saving application settings')
Exemple #6
0
 def saveProject(self):
     if not self.projectSettings.projectName:
         return
     try:
         self.projectSettings.save()
         for image in self.images.values():
             image.save()
     except Exception as err:
         logger.error(err)
         self.ui.errorMsg(values.saveProjectErrorMessage)
 def choose(self, app):
     tunnel = None
     try:
         logger.debug('sockinfo is')
         dump_dict(sockInfo , True)
         tunnel = [s for s in sockInfo if sockInfo.get(s).type == "server_tunnel" and
                   sockInfo.get(s).status == "unused"][0]
     except IndexError, e:
         logger.error("no enough free tunnel")
         return None
Exemple #8
0
    def saveAppSettings(self):
        self.appSettings.mainWindowPos = self.ui.pos
        self.appSettings.mainWindowSize = self.ui.size

        try:
            self.appSettings.save()
        except Exception as err:
            logger.error(err)
            self.ui.errorMsg(
                'An error occurred while trying to save the application settings'
            )
Exemple #9
0
    def loadAppSettings(self):

        try:
            self.appSettings = AppSettings.load()
        except Exception as err:
            logger.error(err)

        self.ui.pos = self.appSettings.mainWindowPos
        self.ui.size = self.appSettings.mainWindowSize

        lastProjectPath = self.appSettings.lastProjectPath
        if utils.fileExists(lastProjectPath):
            self.loadProjectFile(lastProjectPath)
        self.updateRecentProjectsActions()
Exemple #10
0
 def save(self):
     if self.filePath and self.image is not None:
         cv.imwrite(self.filePath, self.image)
         try:
             dataPath = utils.swapExt(self.filePath, '.im')
             with open(dataPath, 'wt') as fp:
                 shapes = {}
                 for name, shapeSet in self.shapes.items():
                     shapes[name] = [shape.data for shape in shapeSet]
                 data = {
                     'name': self.name,
                     'shapes': shapes,
                     'position': self.position,
                     'scale': self.scale,
                     'colormap': self.colormap,
                     'maprange': self.maprange,
                     'transform': self.transform,
                     'flags': self.flags,
                 }
                 jsonData = json.dumps(data)
                 fp.write(jsonData)
         except Exception as err:
             logger.error(err)
Exemple #11
0
    def run(self):

        se = self.projectSettings

        cropField = self.images[IMAGE_CROP_FIELD]
        normField = self.images[IMAGE_NORM_FIELD]
        vegMask = self.images[IMAGE_VEG_MASK]
        vegDensity = self.images[IMAGE_VEG_DENSITY]
        weedMask = self.images[IMAGE_WEED_MASK]
        weedDensity = self.images[IMAGE_WEED_DENSITY]
        roiMask = self.images[IMAGE_ROI_MASK]

        if se.runSegmentVeg:
            vegMask.image = mcrops.veget.segment_vegetation(
                cropField.image, threshold=se.segmentVegThr)
            vegMask.transform = cropField.transform
            vegMask.save()

        if se.runDetectRows:

            (h, w) = vegMask.image.shape
            roiPoly = np.int32([[0, 0], [w, 0], [w, h], [0, h]])

            try:
                if se.roiPolygon is not None:
                    roiPoly = np.array(se.roiPolygon, np.int32)
                elif se.roiAutoDetect:
                    roiPoly = mcrops.veget.detect_roi(
                        vegMask.image,
                        row_sep=se.rowsSeparation,
                        resolution=se.resolution)
                roiPoly = roiPoly.reshape((-1, 1, 2))
                roiPoly = mcrops.utils.trim_poly(roiPoly, (0, 0, w, h))
                cropField.shapes[SHAPE_ROI_POLY] = [
                    Shape(name=SHAPE_ROI_POLY,
                          points=roiPoly.reshape((-1, 2)).tolist(),
                          form=Shape.POLYGON,
                          lineColor=se.roiColor,
                          lineWidth=se.drawLineWidth,
                          visible=se.shapesVisible.get(SHAPE_ROI_POLY, True))
                ]
            except Exception as err:
                logger.error(err)

            rowsDir = se.rowsDirection
            if se.dirAutoDetect:
                rowsDir = mcrops.rows.detect_direction(
                    vegMask.image,
                    resolution=se.resolution,
                    window_shape=(se.rowsDirWindowHeight,
                                  se.rowsDirWindowWidth))

                # Draw an arrow indicating the direction of the crop rows
                pt1 = (int(w / 2), int(h / 2))
                length = min(w / 2, h / 2)
                dx = int(math.cos(rowsDir) * length)
                dy = int(math.sin(rowsDir) * length)
                pt2 = (pt1[0] + min(max(0, dx), w - 1),
                       pt1[1] + min(max(0, dy), h - 1))
                cropField.shapes[SHAPE_ROWS_DIR] = [
                    Shape(name=SHAPE_ROWS_DIR,
                          points=[pt1, pt2],
                          form=Shape.LINE,
                          lineColor=se.rowsDirColor,
                          lineWidth=se.drawLineWidth,
                          visible=se.shapesVisible.get(SHAPE_ROWS_DIR, True))
                ]

            vegMask.image, _, _ = mcrops.veget.norm_image(
                vegMask.image,
                roi_poly=roiPoly,
                rows_direction=rowsDir,
                roi_trim=se.roiTrim,
                is_mask=True)

            normField.image, roiPoly, transform = mcrops.veget.norm_image(
                cropField.image,
                roi_poly=roiPoly,
                rows_direction=rowsDir,
                roi_trim=se.roiTrim)
            transform = transform.tolist()

            if cropField.transform is not None:
                # noinspection PyTypeChecker
                transform = np.dot(cropField.transform, transform).tolist()

            roiMask.image = mcrops.utils.poly_mask(roiPoly,
                                                   vegMask.image.shape)

            normField.transform = transform
            vegMask.transform = transform
            roiMask.transform = transform

            rowsRidges, rowsFurrows = mcrops.rows.detect_rows(
                veg_mask=vegMask.image,
                roi_mask=roiMask.image,
                row_sep=se.rowsSeparation,
                extent_max=se.rowsDetectMaxExtent,
                extent_thr=se.rowsDetectExtentThr,
                fusion_thr=se.rowsDetectFusionThr,
                link_thr=se.rowsDetectLinkThr,
                resolution=se.resolution)

            rowsRidges[:, :, [1, 0]] = rowsRidges[:, :, [0, 1]]
            rowsFurrows[:, :, [1, 0]] = rowsFurrows[:, :, [0, 1]]

            shapes = []
            visible = se.shapesVisible.get(SHAPE_ROWS_RIDGES, True)
            # noinspection PyTypeChecker
            for points in rowsRidges.tolist():
                shapes.append(
                    Shape(name=SHAPE_ROWS_RIDGES,
                          points=points,
                          form=Shape.POLYLINE,
                          lineColor=se.rowsRidgesColor,
                          lineWidth=se.drawLineWidth,
                          visible=visible))
            normField.shapes[SHAPE_ROWS_RIDGES] = shapes
            vegMask.shapes[SHAPE_ROWS_RIDGES] = shapes

            shapes = []
            visible = se.shapesVisible.get(SHAPE_ROWS_FURROWS, True)
            # noinspection PyTypeChecker
            for points in rowsFurrows.tolist():
                shapes.append(
                    Shape(name=SHAPE_ROWS_FURROWS,
                          points=points,
                          form=Shape.POLYLINE,
                          lineColor=se.rowsFurrowsColor,
                          lineWidth=se.drawLineWidth,
                          visible=visible))
            normField.shapes[SHAPE_ROWS_FURROWS] = shapes
            vegMask.shapes[SHAPE_ROWS_FURROWS] = shapes

            cropField.save()
            normField.save()
            vegMask.save()
            roiMask.save()

        if se.runMapVeg:
            densityMap = mcrops.veget.mask_density(
                mask=vegMask.image,
                roi_mask=roiMask.image,
                cell_size=(se.mapsCellWidth, se.mapsCellHeight),
                resolution=se.resolution)

            vegDensity.image = mcrops.utils.array_image(
                values=densityMap, colormap=se.mapsColormap, full_scale=True)
            vegDensity.transform = vegMask.transform
            colormap = mcrops.utils.array_image(
                values=np.arange(0, 255, dtype=np.uint8),
                colormap=se.mapsColormap,
                full_scale=True).reshape((-1, 3))
            # Change BGR format to RGB
            colormap[:, [2, 0]] = colormap[:, [0, 2]]
            vegDensity.colormap = colormap.tolist()
            # noinspection PyArgumentList
            vegDensity.maprange = [
                float(densityMap.min()),
                float(densityMap.max())
            ]
            vegDensity.save()

        if se.runMapWeeds:

            rowsRidges = []
            rowsShapes = vegMask.shapes[SHAPE_ROWS_RIDGES]
            for shape in rowsShapes:
                rowsRidges.append(shape.points)

            weedMask.image = mcrops.weeds.segment_weeds(
                image=normField.image,
                veg_mask=vegMask.image,
                crop_rows=np.array(rowsRidges))

            densityMap = mcrops.veget.mask_density(
                mask=weedMask.image,
                roi_mask=roiMask.image,
                cell_size=(se.mapsCellWidth, se.mapsCellHeight),
                resolution=se.resolution)

            weedDensity.image = mcrops.utils.array_image(
                values=densityMap, colormap=se.mapsColormap, full_scale=True)
            weedDensity.transform = vegMask.transform
            colormap = mcrops.utils.array_image(
                values=np.arange(0, 255, dtype=np.uint8),
                colormap=se.mapsColormap,
                full_scale=True).reshape((-1, 3)).tolist()
            # Change BGR format to RGB
            colormap[:, [2, 0]] = colormap[:, [0, 2]]
            weedDensity.colormap = colormap.tolist()
            # noinspection PyArgumentList
            weedDensity.maprange = [
                float(densityMap.min()),
                float(densityMap.max())
            ]
            weedDensity.save()

        shownImageName = self.projectSettings.shownImageName
        if shownImageName in self.images:
            self.ui.imageView.showImage(self.images[shownImageName])
Exemple #12
0
 def handlePlayerError(self):
     self.ui.playButton.setEnabled(False)
     error = self.player.errorString()
     logger.error(error)