Python skimage.img_as_ubyte() Examples

The following are 30 code examples of skimage.img_as_ubyte(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module skimage , or try the search function .
Example #1
Source File: glcm.py    From Pic-Numero with MIT License 6 votes vote down vote up
def count(filename, model):
    '''
    Returns an estimate of the number of grains in a given wheat image.

    Args:
        filename: Name of image file containing grains to be counted.

        model: regression model for estimating count
    Returns:
        estimation of the number of grains in image.
    '''
    img = misc.imread(filename);
    img_gray = img_as_ubyte(rgb2gray(img));

    glcm = greycomatrix(img_gray, [5], [0], 256, symmetric=True, normed=True)
    dissimilarity = greycoprops(glcm, 'dissimilarity')[0, 0]
    correlation = greycoprops(glcm, 'correlation')[0, 0]
    homogeneity = greycoprops(glcm, 'homogeneity')[0, 0]
    energy = greycoprops(glcm, 'energy')[0, 0]
    feature = np.array([dissimilarity, correlation, homogeneity, energy])

    count = model.predict(feature)
    return count 
Example #2
Source File: MorphologyModule.py    From HistoQC with BSD 3-Clause Clear License 6 votes vote down vote up
def fillSmallHoles(s, params):
    logging.info(f"{s['filename']} - \tfillSmallHoles")
    min_size = int(params.get("min_size", 64))
    img_reduced = morphology.remove_small_holes(s["img_mask_use"], min_size=min_size)
    img_small = img_reduced & np.invert(s["img_mask_use"])

    io.imsave(s["outdir"] + os.sep + s["filename"] + "_small_fill.png", img_as_ubyte(img_small))
    s["img_mask_small_removed"] = (img_small * 255) > 0

    prev_mask = s["img_mask_use"]
    s["img_mask_use"] = img_reduced

    s.addToPrintList("percent_small_tissue_filled",
                     printMaskHelper(params.get("mask_statistics", s["mask_statistics"]), prev_mask, s["img_mask_use"]))

    if len(s["img_mask_use"].nonzero()[0]) == 0:  # add warning in case the final tissue is empty
        logging.warning(f"{s['filename']} - After MorphologyModule.fillSmallHoles: NO tissue "
                        f"remains detectable! Downstream modules likely to be incorrect/fail")
        s["warnings"].append(f"After MorphologyModule.fillSmallHoles: NO tissue remains "
                             f"detectable! Downstream modules likely to be incorrect/fail")
    return 
Example #3
Source File: StructuredForests.py    From StructuredForests with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def bsds500_test(model, input_root, output_root):
    from skimage import img_as_float, img_as_ubyte
    from skimage.io import imread, imsave

    if not os.path.exists(output_root):
        os.makedirs(output_root)

    image_dir = os.path.join(input_root, "BSDS500", "data", "images", "test")
    file_names = filter(lambda name: name[-3:] == "jpg", os.listdir(image_dir))
    n_image = len(file_names)

    for i, file_name in enumerate(file_names):
        img = img_as_float(imread(os.path.join(image_dir, file_name)))

        edge = img_as_ubyte(model.predict(img))

        imsave(os.path.join(output_root, file_name[:-3] + "png"), edge)

        sys.stdout.write("Processing Image %d/%d\r" % (i + 1, n_image))
        sys.stdout.flush()
    print 
Example #4
Source File: MorphologyModule.py    From HistoQC with BSD 3-Clause Clear License 6 votes vote down vote up
def removeSmallObjects(s, params):
    logging.info(f"{s['filename']} - \tremoveSmallObjects")
    min_size = int(params.get("min_size", 64))
    img_reduced = morphology.remove_small_objects(s["img_mask_use"], min_size=min_size)
    img_small = np.invert(img_reduced) & s["img_mask_use"]

    io.imsave(s["outdir"] + os.sep + s["filename"] + "_small_remove.png", img_as_ubyte(img_small))
    s["img_mask_small_filled"] = (img_small * 255) > 0

    prev_mask = s["img_mask_use"]
    s["img_mask_use"] = img_reduced

    s.addToPrintList("percent_small_tissue_removed",
                     printMaskHelper(params.get("mask_statistics", s["mask_statistics"]), prev_mask, s["img_mask_use"]))


    if len(s["img_mask_use"].nonzero()[0]) == 0:  # add warning in case the final tissue is empty
        logging.warning(f"{s['filename']} - After MorphologyModule.removeSmallObjects: NO tissue "
                        f"remains detectable! Downstream modules likely to be incorrect/fail")
        s["warnings"].append(f"After MorphologyModule.removeSmallObjects: NO tissue remains "
                             f"detectable! Downstream modules likely to be incorrect/fail")

    return 
Example #5
Source File: ImageTransform.py    From DRFNS with MIT License 6 votes vote down vote up
def _apply_(self, *image):
        res = ()
        n_img = 0
        for img in image:
            if n_img == 0:
                #pdb.set_trace()
                ### transform image into HSV
                img = img_as_ubyte(color.rgb2hsv(img))
                ### perturbe each channel H, E, Dab
                for i in range(3):
                    k_i = self.params['k'][i] 
                    b_i = self.params['b'][i] 
                    img[:,:,i] = GreyValuePerturbation(img[:, :, i], k_i, b_i, MIN=0., MAX=255)
                    #plt.imshow(img[:,:,i], "gray")
                    #plt.show()
                sub_res = img_as_ubyte(color.hsv2rgb(img))
            else:
                sub_res = img

            res += (sub_res,)
            n_img += 1
        return res 
Example #6
Source File: BasicModule.py    From HistoQC with BSD 3-Clause Clear License 6 votes vote down vote up
def finalProcessingArea(s, params):
    logging.info(f"{s['filename']} - \tfinalProcessingArea")
    area_thresh = int(params.get("area_threshold", "1000"))
    mask = s["img_mask_use"]

    mask_opened = remove_small_objects(mask, min_size=area_thresh)
    mask_removed_area = ~mask_opened & mask

    io.imsave(s["outdir"] + os.sep + s["filename"] + "_areathresh.png", img_as_ubyte(mask_removed_area))

    prev_mask = s["img_mask_use"]
    s["img_mask_use"] = mask_opened > 0

    s.addToPrintList("areaThresh",
                     printMaskHelper(params.get("mask_statistics", s["mask_statistics"]), prev_mask, s["img_mask_use"]))

    if len(s["img_mask_use"].nonzero()[0]) == 0:  # add warning in case the final tissue is empty
        logging.warning(
            f"{s['filename']} - After BasicModule.finalProcessingArea NO tissue remains detectable! Downstream modules likely to be incorrect/fail")
        s["warnings"].append(
            f"After BasicModule.finalProcessingArea NO tissue remains detectable! Downstream modules likely to be incorrect/fail") 
Example #7
Source File: locate_tissue.py    From tissueloc with MIT License 6 votes vote down vote up
def find_tissue_cnts(bw_img):
    """ Fint contours of tissues
    Parameters
    ----------
    bw_img : np.array
        2D binary image.
    Returns
    -------
    cnts: list
        List of all contours coordinates of tissues.
    """

    cnts, _ = cv2.findContours(img_as_ubyte(bw_img), mode=cv2.RETR_EXTERNAL,
                               method=cv2.CHAIN_APPROX_NONE)

    return cnts 
Example #8
Source File: BasicModule.py    From HistoQC with BSD 3-Clause Clear License 6 votes vote down vote up
def finalProcessingSpur(s, params):
    logging.info(f"{s['filename']} - \tfinalProcessingSpur")
    disk_radius = int(params.get("disk_radius", "25"))
    selem = disk(disk_radius)
    mask = s["img_mask_use"]
    mask_opened = binary_opening(mask, selem)
    mask_spur = ~mask_opened & mask

    io.imsave(s["outdir"] + os.sep + s["filename"] + "_spur.png", img_as_ubyte(mask_spur))

    prev_mask = s["img_mask_use"]
    s["img_mask_use"] = mask_opened

    s.addToPrintList("spur_pixels",
                     printMaskHelper(params.get("mask_statistics", s["mask_statistics"]), prev_mask, s["img_mask_use"]))

    if len(s["img_mask_use"].nonzero()[0]) == 0:  # add warning in case the final tissue is empty
        logging.warning(
            f"{s['filename']} - After BasicModule.finalProcessingSpur NO tissue remains detectable! Downstream modules likely to be incorrect/fail")
        s["warnings"].append(
            f"After BasicModule.finalProcessingSpur NO tissue remains detectable! Downstream modules likely to be incorrect/fail") 
Example #9
Source File: object_detection_client.py    From lambda-deep-learning-demo with Apache License 2.0 6 votes vote down vote up
def main():
  parser = argparse.ArgumentParser(
    formatter_class=argparse.ArgumentDefaultsHelpFormatter)

  parser.add_argument("--image_path",
                      help="path for image to run inference",
                      default="~/demo/data/mscoco_fns/val2014/COCO_val2014_000000301397.jpg")

  args = parser.parse_args()

  args.image_path = os.path.expanduser(args.image_path)

  # Read the image
  image = skimage.io.imread(args.image_path, plugin='imageio')
  image = rescale(image, 2.0, anti_aliasing=False)
  image = img_as_ubyte(image)

  data = json.dumps({"signature_name": "predict", "instances": image.tolist()})
  headers = {"content-type": "application/json"}

  response = requests.post(SERVER_URL, data=data, headers=headers)
  response.raise_for_status()
  predictions = response.json()["predictions"]

  display_ori(image, predictions[0]) 
Example #10
Source File: image_utils.py    From ludwig with Apache License 2.0 6 votes vote down vote up
def resize_image(img, new_size_typle, resize_method):
    try:
        from skimage import img_as_ubyte
        from skimage.transform import resize
    except ImportError:
        logger.error(
            ' scikit-image is not installed. '
            'In order to install all image feature dependencies run '
            'pip install ludwig[image]'
        )
        sys.exit(-1)

    if tuple(img.shape[:2]) != new_size_typle:
        if resize_method == CROP_OR_PAD:
            return crop_or_pad(img, new_size_typle)
        elif resize_method == INTERPOLATE:
            return img_as_ubyte(resize(img, new_size_typle))
        raise ValueError(
            'Invalid image resize method: {}'.format(resize_method))
    return img 
Example #11
Source File: art.py    From neural-art with MIT License 6 votes vote down vote up
def print_prog(self, x):
        """
        Save and print progress every self.print_rate iterations.
        """
        if (self.iter % self.print_rate) == 0:
            debug_print("gdesc iteration {}".format(str(self.iter)))
            new_img = self.transformer.deprocess(
                'data',
                x.reshape(self.net.blobs['data'].data.shape)
            )
            imsave(
                '{}/iter-{}.jpg'.format(self.dirname, self.iter),
                skimage.img_as_ubyte(new_img)
            )
            imsave(
                '{}/final.jpg'.format(self.dirname, self.iter),
                skimage.img_as_ubyte(new_img)
            )
        self.iter += 1 
Example #12
Source File: brazilian.py    From sigver with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def iter_genuine(self, user):
        """ Iterate over genuine signatures for the given user"""

        genuine_files = ['a{:03d}_{:02d}.{}'.format(user, img, self.file_extension)
                         for img in range(1, 41)]
        for f in genuine_files:
            full_path = os.path.join(self.path, f)
            img = imread(full_path, as_gray=True)
            yield img_as_ubyte(img), f 
Example #13
Source File: gpds.py    From sigver with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def iter_genuine(self, user):
        """ Iterate over genuine signatures for the given user"""

        user_folder = os.path.join(self.path, '{:03d}'.format(user))
        all_files = sorted(os.listdir(user_folder))
        user_genuine_files = filter(lambda x: x[0:2] == 'c-', all_files)
        for f in user_genuine_files:
            full_path = os.path.join(user_folder, f)
            img = imread(full_path, as_gray=True)
            yield img_as_ubyte(img), f 
Example #14
Source File: cedar.py    From sigver with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def iter_forgery(self, user):
        """ Iterate over skilled forgeries for the given user"""

        files = ['{}_{}_{}.png'.format('forgeries', user, img) for img in range(1, 24 + 1)]
        for f in files:
            full_path = os.path.join(self.path, 'full_forg', f)
            img = imread(full_path, as_gray=True)
            yield img_as_ubyte(img), f 
Example #15
Source File: cedar.py    From sigver with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def iter_genuine(self, user):
        """ Iterate over genuine signatures for the given user"""

        files = ['{}_{}_{}.png'.format('original', user, img) for img in range(1, 24 + 1)]
        for f in files:
            full_path = os.path.join(self.path, 'full_org', f)
            img = imread(full_path, as_gray=True)
            yield img_as_ubyte(img), f 
Example #16
Source File: brazilian.py    From sigver with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def iter_forgery(self, user):
        """ Iterate over skilled forgeries for the given user"""

        if user > 60:
            return  # No forgeries after user 60

        forgery_files = ['a{:03d}_{:02d}.{}'.format(user, img, self.file_extension)
                         for img in range(51, 61)]
        for f in forgery_files:
            full_path = os.path.join(self.path, f)
            img = imread(full_path, as_gray=True)
            yield img_as_ubyte(img), f 
Example #17
Source File: brazilian.py    From sigver with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def iter_simple_forgery(self, user):
        """ Iterate over simple forgeries for the given user"""

        if user > 60:
            return  # No forgeries after user 60

        forgery_files = ['a{:03d}_{:02d}.{}'.format(user, img, self.file_extension)
                         for img in range(41, 51)]
        for f in forgery_files:
            full_path = os.path.join(self.path, f)
            img = imread(full_path, as_gray=True)
            yield img_as_ubyte(img), f 
Example #18
Source File: dataset_loader.py    From deep_demosaick with MIT License 5 votes vote down vote up
def __getitem__(self, idx):
        img_name_gt = os.path.join(self.root_dir,  self.groundtruth,
                                   self.listfiles_gt[idx])
        img_name_input = os.path.join(self.root_dir,  self.input,
                                      self.listfiles_gt[idx])

        image_gt = cv2.imread(img_name_gt)
        b, g, r = cv2.split(image_gt)       # get b,g,r
        image_gt = cv2.merge([r, g, b])     # switch it to rgb

        image_input = io.imread(img_name_input, )

        # perform mask computation
        mask = self.compute_mask(self.pattern, image_input.shape)
        mask = mask.astype(np.int32)
        image_mosaic = np.zeros(image_gt.shape).astype(np.int32)

        image_mosaic[:, :, 0] = mask[..., 0] * image_input
        image_mosaic[:, :, 1] = mask[..., 1] * image_input
        image_mosaic[:, :, 2] = mask[..., 2] * image_input
        #print(image_mosaic.dtype)
        image_input = np.sum(image_mosaic, axis=2, dtype='uint16')
        # perform bilinear interpolation for bayer_rggb images
        if self.apply_bilinear:
            image_mosaic = self.preprocess(self.pattern, image_input)

        image_gt = img_as_ubyte(image_gt)
        image_input = image_mosaic.astype(np.float32)/65535*255
        #assert image_gt.dtype == 'float64'
        #assert image_input.dtype == 'float64'

        sample = {'image_gt': image_gt,
                  'image_input': image_input,
                  'filename': self.listfiles_gt[idx],
                  'mask':mask}

        if self.transform:
            sample = self.transform(sample)

        return sample 
Example #19
Source File: mcm_dataset_loader.py    From deep_demosaick with MIT License 5 votes vote down vote up
def __getitem__(self, idx):
        img_name_gt = os.path.join(self.root_dir, self.listfiles_gt[idx])

        image_gt = cv2.imread(img_name_gt)
        b, g, r = cv2.split(image_gt)       # get b,g,r
        image_gt = cv2.merge([r, g, b])     # switch it to rgb

        # perform mask computation
        mask = self.compute_mask(self.pattern, image_gt.shape[:2])
        mask = mask.astype(np.uint8)
        image_mosaic = np.zeros_like(image_gt)

        image_mosaic = mask * image_gt
        image_input = np.sum(image_mosaic, axis=2, dtype='uint8')
        # perform bilinear interpolation for bayer_rggb images
        if self.apply_bilinear:
            image_mosaic = self.preprocess(self.pattern, image_input)

        image_gt = img_as_ubyte(image_gt)
        image_input = img_as_ubyte(image_mosaic)
        #assert image_gt.dtype == 'float64'
        #assert image_input.dtype == 'float64'

        sample = {'image_gt': image_gt,
                  'image_input': image_input,
                  'filename': self.listfiles_gt[idx],
                  'mask': mask}

        if self.transform:
            sample = self.transform(sample)

        return sample 
Example #20
Source File: kodak_dataset_loader.py    From deep_demosaick with MIT License 5 votes vote down vote up
def __getitem__(self, idx):
        img_name_gt = os.path.join(self.root_dir, self.listfiles_gt[idx])

        image_gt = cv2.imread(img_name_gt)
        b, g, r = cv2.split(image_gt)       # get b,g,r
        image_gt = cv2.merge([r, g, b])     # switch it to rgb

        # perform mask computation
        mask = self.compute_mask(self.pattern, image_gt.shape[:2])
        mask = mask.astype(np.uint8)
        image_mosaic = np.zeros_like(image_gt)

        image_mosaic = mask * image_gt
        image_input = np.sum(image_mosaic, axis=2, dtype='uint8')
        # perform bilinear interpolation for bayer_rggb images
        if self.apply_bilinear:
            image_mosaic = self.preprocess(self.pattern, image_input)

        image_gt = img_as_ubyte(image_gt)
        image_input = img_as_ubyte(image_mosaic)
        #assert image_gt.dtype == 'float64'
        #assert image_input.dtype == 'float64'

        sample = {'image_gt': image_gt,
                  'image_input': image_input,
                  'filename': self.listfiles_gt[idx],
                  'mask': mask}

        if self.transform:
            sample = self.transform(sample)

        return sample 
Example #21
Source File: tf_eval.py    From 3d-dl with MIT License 5 votes vote down vote up
def adaptive_equalize(img):
    # Adaptive Equalization
    img = img_as_float(img)
    img_adapteq = exposure.equalize_adapthist(img, clip_limit=0.05)
    return img_as_ubyte(img_adapteq) 
Example #22
Source File: test.py    From 3d-dl with MIT License 5 votes vote down vote up
def adaptive_equalize(img):
    # Adaptive Equalization
    img = img_as_float(img)
    img_adapteq = exposure.equalize_adapthist(img, clip_limit=0.05)
    return img_as_ubyte(img_adapteq) 
Example #23
Source File: AnnotationModule.py    From HistoQC with BSD 3-Clause Clear License 5 votes vote down vote up
def geoJSONMask(s, params):
    logging.info(f"{s['filename']} - \tgeoJSONMask")
    mask = s["img_mask_use"]

    geojson_basepath = params.get("geojson_filepath",None)
    geojson_suffix = params.get("geojson_suffix", "")
    if not geojson_basepath:
        geojson_basepath = s["dir"]

    fname = geojson_basepath + os.sep + PurePosixPath(s['filename']).stem + geojson_suffix + '.json'
    if not Path(fname).is_file():
        msg = f"Annotation file {fname} does not exist. Skipping."
        logging.warning(f"{s['filename']} - {msg}")
        s["warnings"].append(msg)
        return

    logging.info(f"{s['filename']} - \tusing {fname}")

    point_sets = get_points_from_geojson(s, fname)
    annotationMask = mask_out_annotation(s, point_sets) > 0
    io.imsave(s["outdir"] + os.sep + s["filename"] + "_geoJSONMask.png", img_as_ubyte(annotationMask))

    prev_mask = s["img_mask_use"]
    s["img_mask_use"] = prev_mask & annotationMask

    s.addToPrintList("geoJSONMask",
                     printMaskHelper(params.get("mask_statistics", s["mask_statistics"]), prev_mask, s["img_mask_use"]))

    if len(s["img_mask_use"].nonzero()[0]) == 0:  # add warning in case the final tissue is empty
        logging.warning(
            f"{s['filename']} - After AnnotationModule.geoJSONMask NO tissue remains detectable! Downstream modules likely to be incorrect/fail")
        s["warnings"].append(
            f"After AnnotationModule.geoJSONMask NO tissue remains detectable! Downstream modules likely to be incorrect/fail")

    return 
Example #24
Source File: generate_mask.py    From MaskInsightface with Apache License 2.0 5 votes vote down vote up
def generate_mask(image, prn, max_bbox, bool_mask = True):
    if image.shape[2] > 3:
        image = image[:, :, :3]

    # the core: regress position map
    pos = prn.process(image, max_bbox)  # use dlib to detect face
    if pos is None:
        print('depths_img is error')
        return None
    else:
        # 3D vertices with 68
        landmarks = np.float32(prn.get_landmarks(pos))
        if bool_mask:
            # 3D vertices with 40k
            vertices = prn.get_vertices(pos)
            h, w = image.shape[:2]
            # use depth generate mask
            depth_image = get_depth_image(vertices, prn.triangles, h, w, True)# use crender_colors plot img, so fast but not as good as render_texture
            mask = img_as_ubyte(depth_image)

            if (mask.max() <= 1 and mask.min() >= 0):
                mask = img_as_ubyte(mask)
                img_mask = image * mask[:, :, np.newaxis]
                # 空白处添加median人脸色
                img_mask = add_median_colr(image, img_mask, mask, max_bbox)
                # 直接使用3d的人脸对齐方法
                aligned = align_face(img_mask, landmarks[:, :2], prn.canonical_vertices_fan, target_size=(318, 361))
                return aligned
            else:
                print('depths_img is error')
                return None
        else:
            # 直接使用3d的人脸对齐方法
            aligned = align_face(image, landmarks, prn.canonical_vertices_fan, target_size=(318, 361))
            return aligned 
Example #25
Source File: gui.py    From Pic-Numero with MIT License 5 votes vote down vote up
def didClickSubmitButton(self, event):
        print(self.imageFilePath)
        img = img_as_ubyte(io.imread(CLUSTER_IMAGE_FILENAME))
        roi_img = spectral_roi.extract_roi(img, gui_checkbox_handlers.getSelectedClusters())
        roi_img_filename = "{}.png".format(Helper.generate_random_id())
        io.imsave(roi_img_filename, roi_img)
        Display.show_image(roi_img, roi_img_filename) 
Example #26
Source File: datautils.py    From panotti with MIT License 5 votes vote down vote up
def scale_to_uint8(float_img):
    #out_img = 255*(float_img - np.min(float_img))/np.ptp(float_img).astype(np.uint8)
    out_img = img_as_ubyte( (float_img-np.min(float_img))/np.ptp(float_img) )
    return out_img 
Example #27
Source File: BubbleRegionByRegion.py    From HistoQC with BSD 3-Clause Clear License 5 votes vote down vote up
def detectSmoothness(s, params):
        logging.info(f"{s['filename']} - \tBubbleRegionByRegion.detectSmoothness")
        thresh = float(params.get("threshold", ".01" ))
        kernel_size = int(params.get("kernel_size", "10"))
        min_object_size = int(params.get("min_object_size", "100"))

        img = s.getImgThumb(s["image_work_size"])
        img = color.rgb2gray(img)
        avg = np.ones((kernel_size, kernel_size)) / (kernel_size**2)

        imf = scipy.signal.convolve2d(img, avg, mode="same")
        mask_flat = abs(imf - img) < thresh

        mask_flat = remove_small_objects(mask_flat, min_size=min_object_size)
        mask_flat = ~remove_small_objects(~mask_flat, min_size=min_object_size)

        prev_mask = s["img_mask_use"]
        s["img_mask_flat"] = mask_flat

        io.imsave(s["outdir"] + os.sep + s["filename"] + "_flat.png", img_as_ubyte(mask_flat & prev_mask))

        s["img_mask_use"] = s["img_mask_use"] & ~s["img_mask_flat"]


        s.addToPrintList("flat_areas",
                         printMaskHelper(params.get("mask_statistics", s["mask_statistics"]), prev_mask,
                                         s["img_mask_use"]))

        if len(s["img_mask_use"].nonzero()[0]) == 0:  # add warning in case the final tissue is empty
            logging.warning(f"{s['filename']} - After BubbleRegionByRegion.detectSmoothness: NO tissue "
                            f"remains detectable! Downstream modules likely to be incorrect/fail")
            s["warnings"].append(f"After BubbleRegionByRegion.detectSmoothness: NO tissue remains "
                                 f"detectable! Downstream modules likely to be incorrect/fail")

        return 
Example #28
Source File: image_tfs.py    From tanda with MIT License 5 votes vote down vote up
def np_to_pil(x):
    """Converts from np image in skimage float format to PIL.Image"""
    x = np.squeeze(np.uint8(img_as_ubyte(x)))
    return Image.fromarray(np.uint8(img_as_ubyte(x))) 
Example #29
Source File: BlurDetectionModule.py    From HistoQC with BSD 3-Clause Clear License 5 votes vote down vote up
def identifyBlurryRegions(s, params):
    logging.info(f"{s['filename']} - \tidentifyBlurryRegions")

    blur_radius = int(params.get("blur_radius", 7))
    blur_threshold = float(params.get("blur_threshold", .1))

    img = s.getImgThumb(params.get("image_work_size", "2.5x"))
    img = rgb2gray(img)
    img_laplace = np.abs(skimage.filters.laplace(img))
    mask = skimage.filters.gaussian(img_laplace, sigma=blur_radius) <= blur_threshold

    mask = skimage.transform.resize(mask, s.getImgThumb(s["image_work_size"]).shape, order=0)[:, :,
           1]  # for some reason resize takes a grayscale and produces a 3chan
    mask = s["img_mask_use"] & (mask > 0)

    io.imsave(s["outdir"] + os.sep + s["filename"] + "_blurry.png", img_as_ubyte(mask))
    s["img_mask_blurry"] = (mask * 255) > 0

    prev_mask = s["img_mask_use"]
    s["img_mask_use"] = s["img_mask_use"] & ~s["img_mask_blurry"]

    s.addToPrintList("percent_blurry",
                     printMaskHelper(params.get("mask_statistics", s["mask_statistics"]), prev_mask, s["img_mask_use"]))

    if len(s["img_mask_use"].nonzero()[0]) == 0:  # add warning in case the final tissue is empty
        logging.warning(
            f"{s['filename']} - After BlurDetectionModule.identifyBlurryRegions NO tissue remains detectable! Downstream modules likely to be incorrect/fail")
        s["warnings"].append(
            f"After BlurDetectionModule.identifyBlurryRegions NO tissue remains detectable! Downstream modules likely to be incorrect/fail")


    return 
Example #30
Source File: AnnotationModule.py    From HistoQC with BSD 3-Clause Clear License 5 votes vote down vote up
def xmlMask(s, params):
    logging.info(f"{s['filename']} - \txmlMask")
    mask = s["img_mask_use"]

    xml_basepath = params.get("xml_filepath",None)
    xml_suffix = params.get("xml_suffix", "")
    if not xml_basepath:
        xml_basepath = s["dir"]

    xml_fname = xml_basepath + os.sep + PurePosixPath(s['filename']).stem + xml_suffix + '.xml'
    if not Path(xml_fname).is_file():
        msg = f"Annotation file {xml_fname} does not exist. Skipping."
        logging.warning(f"{s['filename']} - {msg}")
        s["warnings"].append(msg)
        return

    logging.info(f"{s['filename']} - \tusing {xml_fname}")

    point_sets = get_points_from_xml(xml_fname)
    annotationMask = mask_out_annotation(s, point_sets) > 0
    io.imsave(s["outdir"] + os.sep + s["filename"] + "_xmlMask.png", img_as_ubyte(annotationMask))

    prev_mask = s["img_mask_use"]
    s["img_mask_use"] = prev_mask & annotationMask

    s.addToPrintList("xmlMask",
                     printMaskHelper(params.get("mask_statistics", s["mask_statistics"]), prev_mask, s["img_mask_use"]))

    if len(s["img_mask_use"].nonzero()[0]) == 0:  # add warning in case the final tissue is empty
        logging.warning(
            f"{s['filename']} - After AnnotationModule.xmlMask NO tissue remains detectable! Downstream modules likely to be incorrect/fail")
        s["warnings"].append(
            f"After AnnotationModule.xmlMask NO tissue remains detectable! Downstream modules likely to be incorrect/fail")

    return