예제 #1
0
    def execute(self, param, **kwargs):
        wrapper = self.init_wrapper(**kwargs)
        if wrapper is None:
            return False

        res = False
        try:
            if param.name == "draw_roi":
                img = wrapper.current_image
                ori_height, ori_width = img.shape[:2]
                factor = ori_width / 800
                img = resize_image(
                    img,
                    width=ori_width // factor,
                    height=ori_height // factor,
                    keep_aspect_ratio=True,
                )
                r = cv2.selectROI(windowName="Draw ROI", img=img)
                cv2.destroyAllWindows()
                r = (
                    int(r[0] * factor),
                    int(r[1] * factor),
                    int(r[2] * factor),
                    int(r[3] * factor),
                )

                self.set_value_of(key="cx",
                                  value=r[0] + r[2] // 2,
                                  update_widgets=True)
                self.set_value_of(key="cy",
                                  value=r[1] + r[2] // 2,
                                  update_widgets=True)
                self.set_value_of(key="radius",
                                  value=r[2] // 2,
                                  update_widgets=True)

                res = True
            else:
                res = False
        except Exception as e:
            logger.error(f'Failed to execute: "{repr(e)}"',
                         target_logger=logger)
            res = False
        else:
            pass
        finally:
            if res:
                return "process_wrapper"
            else:
                return ""
    def process_wrapper(self, **kwargs):
        """
        Local binary pattern threshold:
        Gray scale and rotation invariant LBP (Local Binary Patterns).
                LBP is an invariant descriptor that can be used for texture classification.
        Real time: False

        Keyword Arguments (in parentheses, argument name):
            * Activate tool (enabled): Toggle whether or not tool is active
            * Channel (channel):
            * Number of circularly symmetric neighbor (P): Number of circularly symmetric neighbor set points (quantization of the angular space)
            * Radius of circle (R): Radius of circle (spatial resolution of the operator)
            * Method to determine the pattern (method):
            * Transformation applied to output (transformation):
            * Cut x%% lower values (lower_cut): Increase to smooth low frequency textures regions and add detail to high frequencies
            * Cut x%% upper values (upper_cut): Increase to smooth high frequency textures regions and add detail to low frequencies
            * Postprocessing option (post_processing):
            * Threshold min value (min_t):
            * Threshold max value (max_t):
            * Median filter size (odd values only) (median_filter_size):
            * Morphology operator (morph_op):
            * Kernel size (kernel_size):
            * Kernel shape (kernel_shape):
            * Iterations (proc_times):
            * Select pseudo color map (color_map):
        """

        wrapper = self.init_wrapper(**kwargs)
        if wrapper is None:
            return False

        res = False
        try:
            if self.get_value_of("enabled") == 1:
                c = ipc.resize_image(
                    wrapper.get_channel(
                        wrapper.current_image, self.get_value_of("channel")
                    ),
                    target_rect=RectangleRegion(width=800, height=600),
                    keep_aspect_ratio=True,
                    output_as_bgr=False,
                )
                c = local_binary_pattern(
                    image=c,
                    P=self.get_value_of("P", scale_factor=wrapper.scale_factor),
                    R=self.get_value_of("R", scale_factor=wrapper.scale_factor),
                    method=self.get_value_of("method"),
                )

                # Transform
                ct = self.get_value_of(f"transformation")
                if ct == "sigmoid":
                    c = np.interp(c, (c.min(), c.max()), (0, 5))
                    c = expit(c)
                elif ct == "log":
                    c = np.log(c + 1)
                elif ct == "logit":
                    c = np.interp(c, (c.min(), c.max()), (0.5, 0.99))
                    c = logit(c)
                elif ct == "arcsin":
                    c = np.interp(c, (c.min(), c.max()), (0, 1))
                    c = np.arcsin(c)
                elif ct == "sqrt":
                    c = np.interp(c, (c.min(), c.max()), (0, 1))
                    c = np.sqrt(c)

                # Cut
                lower_cut = self.get_value_of("lower_cut")
                if lower_cut > 0:
                    c[c < np.max(c) * (lower_cut / 100)] = 0
                upper_cut = self.get_value_of("upper_cut")
                if upper_cut > 0:
                    upper_cut = np.max(c) * ((100 - upper_cut) / 100)
                    c[c > upper_cut] = upper_cut

                c = self.to_uint8(c)

                # Post processing
                pp = self.get_value_of("post_processing")
                if pp == "threshold":
                    median_filter_size = self.get_value_of("median_filter_size")
                    median_filter_size = (
                        0
                        if median_filter_size == 1
                        else ipc.ensure_odd(median_filter_size)
                    )
                    c, _ = wrapper.get_mask(
                        src_img=c,
                        channel=None,
                        min_t=self.get_value_of("min_t"),
                        max_t=self.get_value_of("max_t"),
                        median_filter_size=median_filter_size,
                    )
                    self.result = self.apply_morphology_from_params(c)
                elif pp == "false_color":
                    color_map = self.get_value_of("color_map")
                    _, color_map = color_map.split("_")
                    self.result = cv2.applyColorMap(c, int(color_map))
                else:
                    self.result = c

                # Store
                wrapper.store_image(self.result, "local_binary_pattern")
                res = True
            else:
                wrapper.store_image(wrapper.current_image, "current_image")
                res = True
        except Exception as e:
            res = False
            logger.error(f'Failed to process {self. name}: "{repr(e)}"')
        else:
            pass
        finally:
            return res
예제 #3
0
    def process_wrapper(self, **kwargs):
        """
        Copy or rename image:
        Copies an image, renaming it if needed
        Real time: False

        Keyword Arguments (in parentheses, argument name):
            * Activate tool (enabled): Toggle whether or not tool is active
            * Target folder (path): Can be overridden at process call
            * Image to copy (source_image):
            * Custom image name (named_source):
            * Image output format (output_format):
            * Output naming convention (output_name):
            * Prefix or suffix (prefix_suffix):
            * Name of ROI to be used (roi_names): Operation will only be applied inside of ROI
            * ROI selection mode (roi_selection_mode):
            * Resize images if with is larger than (max_width):
            * Resize images if height is larger than (max_height):
            * Keep aspect ratio (kar):
        """

        wrapper = self.init_wrapper(**kwargs)
        if wrapper is None:
            return False

        res = False
        try:
            self.data_dict = {}
            if self.get_value_of("enabled") == 1:
                # Get source image
                source = self.get_value_of("source_image")
                var_name = source
                if source == "source":
                    img = wrapper.source_image
                elif source == "custom":
                    var_name = self.get_value_of("named_source")
                    img = wrapper.retrieve_stored_image(var_name)
                else:
                    img = None
                    logger.error(f"Copy or rename image FAILED, unknown source: {source}")
                    return
                if img is None:
                    logger.error(f"Copy or rename image FAILED, missing source: {source}")
                    return

                # Apply ROIs
                rois = self.get_ipt_roi(
                    wrapper=wrapper,
                    roi_names=self.get_value_of("roi_names").replace(" ", "").split(","),
                    selection_mode=self.get_value_of("roi_selection_mode"),
                )
                img = wrapper.apply_roi_list(img=img, rois=rois)

                dst_path = self.build_path()

                # Add image to list
                wrapper.store_image(image=img, text="copied_or_renamed_image")

                # Add data
                self.add_value(key="source_name", value=wrapper.name, force_add=True)
                if "image" not in var_name:
                    var_name += "_image"
                self.add_value(key=var_name, value=dst_path, force_add=True)

                # Resize if needed
                max_width = self.get_value_of("max_width")
                max_height = self.get_value_of("max_height")
                kar = self.get_value_of("kar") == 1

                if max_width != 0 and max_height != 0:
                    r = regions.RectangleRegion(width=max_width, height=max_height)
                elif max_width == 0 and max_height != 0:
                    r = regions.RectangleRegion(width=wrapper.width, height=max_height)
                elif max_width != 0 and max_height == 0:
                    r = regions.RectangleRegion(width=max_width, height=wrapper.height)
                else:
                    r = None
                if r is not None:
                    img = ipc.resize_image(
                        src_img=img, target_rect=r, keep_aspect_ratio=kar
                    )

                # Copy image
                force_directories(self.output_path)
                cv2.imwrite(filename=dst_path, img=img)
                res = True
            else:
                wrapper.store_image(wrapper.current_image, "current_image")
                res = True
        except Exception as e:
            res = False
            logger.exception(f'Failed to process {self. name}: "{repr(e)}"')
        else:
            pass
        finally:
            self.result = res
            return res
예제 #4
0
    def process_wrapper(self, **kwargs):
        """
        Match image and mask resolution:
        'Matches mask and current image resolution
        Real time: True

        Keyword Arguments (in parentheses, argument name):
            * Activate tool (enabled): Toggle whether or not tool is active
            * Match resolution to (match_to):"""

        wrapper = self.init_wrapper(**kwargs)
        if wrapper is None:
            return False

        res = False
        try:
            if self.get_value_of("enabled") == 1:
                img = wrapper.current_image
                mask = self.get_mask()
                if mask is None:
                    logger.error(
                        "Failure Match image and mask resolution: mask must be initialized"
                    )
                    return
                match_to = self.get_value_of("match_to")

                if match_to == "mask":
                    wrapper.current_image = ipc.resize_image(
                        src_img=img,
                        width=mask.shape[1],
                        height=mask.shape[0],
                        keep_aspect_ratio=False,
                    )
                    self.result = wrapper.current_image
                elif match_to == "image":
                    wrapper.mask = ipc.resize_image(
                        src_img=mask,
                        width=img.shape[1],
                        height=img.shape[0],
                        keep_aspect_ratio=False,
                        output_as_bgr=False,
                    )
                    wrapper.mask[wrapper.mask != 0] = 255
                    self.result = wrapper.mask

                self.demo_image = wrapper.build_mosaic(
                    shape=(
                        wrapper.current_image.shape[0] * 2,
                        wrapper.current_image.shape[1],
                        wrapper.current_image.shape[2],
                    ),
                    image_names=[[wrapper.current_image], [wrapper.mask]],
                )

                # Write your code here
                wrapper.store_image(img, "current_image")
                res = True
            else:
                wrapper.store_image(wrapper.current_image, "current_image")
                res = True
        except Exception as e:
            res = False
            logger.error(
                f"Match image and mask resolution FAILED, exception: {repr(e)}"
            )
        else:
            pass
        finally:
            return res