コード例 #1
0
    def __getitem__(self, index):
        mid = self.mid_list[index]
        img_name = self.file_list[index]
        level = self.level_list[index]
        olevel = self.olevel_list[index]

        file_path = os.path.join(self.dataroot, mid, 'slide_files/', level,
                                 img_name)
        img = pil_loader(file_path)

        if self.img_transforms is not None:
            img = self.img_transforms(img)

        if isinstance(img, list):
            # In case we used a transforms that gives several images from one.
            stack = [np.array(img_) for img_ in img]
            # Stain normalisation.
            if self.stain_normaliser:
                stack = [self.stain_normaliser(img_) for img_ in stack]

            # H&E decomposition.
            if self.hed_decomp:
                stack = [
                    skcolor.rgb2hed(img_ / 255.0).astype(np.float32)
                    for img_ in stack
                ]
                stack = [img_[:, :, self.hed_channels] for img_ in stack]

            if self.use_colour_transform and self.if_train:
                stack = [self.colour_transform(img_) for img_ in stack]
            stack = [self.normalise(img_) for img_ in stack]
            img = torch.stack(stack)
        else:
            # Convert to Numpy array from PIL Image.
            img = np.array(img)
            # Stain normalisation.
            if self.stain_normaliser:
                img = self.stain_normaliser(img)

            # H&E decomposition.
            if self.hed_decomp:
                img = skcolor.rgb2hed(img / 255.0).astype(np.float32)
                img = img[:, :, self.hed_channels]

            if self.use_colour_transform and self.if_train:
                img = self.colour_transform(img)

            img = self.normalise(img)

        # Added img_name[:-4] on 2019-11-30 to accomodate for
        # adjacency graph.
        return (img, olevel, img_name[:-4], img_name[:-4])
コード例 #2
0
 def transform(img):
     # Colour augmentation by breaking the image apart into H & E stains, and modifying their concentration.
     hed = skcolor.rgb2hed(img / 255.0)
     alphas = np.random.normal(size=(1, 1, 3), loc=mean, scale=std)
     hed = hed * alphas
     img = skcolor.hed2rgb(hed).astype(np.float32)
     return img
コード例 #3
0
ファイル: augs.py プロジェクト: nsh23/hover_fork
 def _augment(self, img, s):
     img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
     image = rgb2hed(img)
     image[..., 0] = equalize_hist(image[..., 0])
     image[..., 1] = equalize_hist(image[..., 1])
     image[..., 2] = equalize_hist(image[..., 2])
     return img_as_ubyte(image)
コード例 #4
0
ファイル: randaugment.py プロジェクト: violet998/SSL_CR_Histo
def colour_augmentation(image, h_mean, h_std, d_mean, d_std, e_mean, e_std):

    ihc_hed = rgb2hed(image)
    Im_size = image.shape[1]

    h = ihc_hed[:, :, 0]
    d = ihc_hed[:, :, 1]
    e = ihc_hed[:, :, 2]

    hFlat = np.ravel(h, order='A')
    dFlat = np.ravel(d, order='A')
    eFlat = np.ravel(e, order='A')

    # Method
    hmod = random.normalvariate(h_mean, h_std)
    dmod = random.normalvariate(d_mean, d_std)
    emod = random.normalvariate(e_mean, e_std)

    for x in range(len(h.ravel())):
        hFlat[x] = hFlat[x] + hmod
        dFlat[x] = dFlat[x] + dmod
        eFlat[x] = eFlat[x] + emod

    ##############
    h = hFlat.reshape(Im_size, Im_size)
    d = dFlat.reshape(Im_size, Im_size)
    e = eFlat.reshape(Im_size, Im_size)

    zdh = np.stack((h, d, e), 2)
    zdh = hed2rgb(zdh)
    zdh_8bit = (zdh * 255).astype('uint8')
    image = zdh_8bit
    return image
コード例 #5
0
def rgb_to_hed(img: PIL.Image.Image) -> PIL.Image.Image:
    """Convert RGB channels to HED channels.

    image color space (RGB) is converted to Hematoxylin-Eosin-Diaminobenzidine space.

    Parameters
    ----------
    img : PIL.Image.Image
        Input image

    Returns
    -------
    PIL.Image.Image
        Image in HED space
    """
    if img.mode not in ["RGB", "RGBA"]:
        raise Exception("Input image must be RGB.")
    if img.mode == "RGBA":
        img_arr = np.array(sk_color.rgba2rgb(img))
        warn("Input image must be RGB. "
             "NOTE: the image will be converted to RGB before HED conversion.")
    else:
        img_arr = np.array(img)
    hed_arr = sk_color.rgb2hed(img_arr)
    hed = np_to_pil(hed_arr)

    return hed
コード例 #6
0
ファイル: finaledgegcncopy.py プロジェクト: zhangjun001/FGNet
    def __getitem__(self, index):
        if self.ratio_counter == self.negative_index:
            index = index % len(self.negative_images)
            data_file = self.negative_image_files[index]
        else:
            index = index % len(self.positive_images)
            data_file = self.positive_image_files[index]

        self.ratio_counter += 1
        if self.ratio_counter > self.positive_negative_ratio:
            self.negative_index = np.random.randint(
                low=0, high=self.positive_negative_ratio + 1)
            self.ratio_counter = 0
        image = cv2.imread(data_file["img"])
        image = cv2.resize(image, (OUTPUT_SIZE, OUTPUT_SIZE))
        angle = np.random.randint(4)
        image = rotate(image, angle)
        image = cv2.flip(image, np.random.randint(2) - 1)
        if args.color_channel_separation:
            ihc_hed = rgb2hed(image)
            h = rescale_intensity(ihc_hed[:, :, 0], out_range=(0, 1))
            d = rescale_intensity(ihc_hed[:, :, 2], out_range=(0, 1))
            image = np.dstack((np.zeros_like(h), d, h))
            #image = zdh.transpose(2, 0, 1).astype('float32')/255
        name = data_file["img"]
        path, file = os.path.split(name)
        split_filename = file.split("_")
        gt_percent = float(split_filename[0])
        moe = float(split_filename[1])
        image = self.toTensor(image)
        return (image, name, gt_percent, moe)
コード例 #7
0
def segment_rgb(rgb: np.ndarray, parameters=None) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
    """Returns (tissue, nucleus, no_class)
    :param rgb: RGB NumPy array
    :param parameters:
    :return: A tuple of NumPy arrays (Tissue, Nucleus, N_class)
    """
    return segment_sample(normalize_channels(rgb2hed(rgb)), parameters=parameters)
コード例 #8
0
ファイル: routines.py プロジェクト: makama-md/patch2image
def _process_img(img,
                 gt,
                 gamma=0,
                 clahe=False,
                 gray=False,
                 xyz=False,
                 hed=False,
                 horizontal_flip=False,
                 width_shift_range=0,
                 height_shift_range=0,
                 vertical_flip=0,
                 rotate_range=0):
    img = exposure.rescale_intensity(img.astype(float), out_range=(0, 1))
    if gray:
        img = color.rgb2gray(img)
    if xyz:
        img = color.rgb2xyz(img)
    if hed:
        img = color.rgb2hed(img)
    img = exposure.rescale_intensity(img, out_range=(0, 1))
    if clahe:
        img = exposure.equalize_adapthist(img)
    if gamma:
        img = exposure.adjust_gamma(img, gamma)
        img = exposure.rescale_intensity(img, out_range=(0, 1))
    if img.ndim == 2:
        img = np.expand_dims(img, -1)

    img, gt = flip_img(img, gt, horizontal_flip, vertical_flip)
    img, gt = shift_img(img, gt, width_shift_range, height_shift_range,
                        rotate_range)

    return img, gt
コード例 #9
0
def render_hed(patch_path, figsize: Tuple[int] = (11, 3)) -> None:
    # lecture d'un patch
    patch = Image.open(patch_path)
    # conversion du RGB au HED
    ihc_hed = rgb2hed(patch)
    # filtrage des pixels négatifs
    ihc_hed[ihc_hed < 0] = 0
    # construction des 3 canaux H, E et D
    null = np.zeros_like(ihc_hed[:, :, 0])
    ihc_h = hed2rgb(np.stack((ihc_hed[:, :, 0], null, null),
                             axis=-1))  #Hematoxylin channel
    ihc_e = hed2rgb(np.stack((null, ihc_hed[:, :, 1], null), axis=-1))  #Eosin
    ihc_d = hed2rgb(np.stack((null, null, ihc_hed[:, :, 2]), axis=-1))  #DAB
    # rendu graphique
    fig, axes = plt.subplots(1, 4, figsize=figsize, sharex=True, sharey=True)
    ax = axes.ravel()

    ax[0].imshow(patch)
    ax[0].set_title("Patch d'origine")

    ax[1].imshow(ihc_h)
    ax[1].set_title("Hématoxyline")

    ax[2].imshow(ihc_e)
    ax[2].set_title("Eosine")

    ax[3].imshow(ihc_d)
    ax[3].set_title("Diaminobenzidine")

    for a in ax.ravel():
        a.axis('off')
    fig.tight_layout()
    plt.show()
コード例 #10
0
def load_list_files(filename):
    """
    load all data form the file of list data
    """
    files = []
    data = []
    hist_data = []
    labels = []
    with open(filename, "r") as f:
        files = [line.strip() for line in f.readlines()]

    for img in files:
        label = img[-5:-4]
        labels.append(float(label))
        image = cv2.imread(img, flags=1)
        hed = cv2.split(rgb2hed(image))[1]
        hed = img_as_ubyte(hed)
        hist = cv2.calcHist([hed], [0], None, [256], [0, 256]).flatten()
        hist_data.append(hist)
        _, region = preprocessor.run(image)
        region = cv2.resize(region, (256, 256))
        lbp_hist, lbp_img = lbp.compute(region)
        # com.debug_im(lbp_img)
        lbp_img = cv2.resize(lbp_img, (30, 30))
        lbp_img = np.nan_to_num(lbp_img)
        data.append(lbp_img.flatten())
        # data.append(lbp_hist)

    data = np.array(data, dtype=np.float32)
    hist_data = np.array(hist_data, dtype=np.float32)
    return data, labels, hist_data
コード例 #11
0
ファイル: ihc_analysis.py プロジェクト: AidanRoss/histology
def color_conversion(img):
    # This function converts rgb image to the IHC color space, where channel 1 is Hematoxylin, 2 in Eosin and 3 is DAB

    ihc_rgb = skimage.io.imread(img)
    ihc_hed = rgb2hed(ihc_rgb)

    return ihc_rgb, ihc_hed
コード例 #12
0
def deconvolveColors(image):
    """
    Separates H&E channels from an RGB image using skimage.color.rgb2hed
    method.

    Parameters
    ----------

    image : 3D numpy array
        RGB image in the format [X, Y, C] where the hematoxylin and
        eosin channels are to be separted.

    Returns
    -------

    hematoxylin : 2D numpy array
        nuclear channel deconvolved from RGB image


    eosin : 2D numpy array
        cytoplasm channel deconvolved from RGB image

    """

    separated_image = rgb2hed(image)

    hematoxylin = separated_image[:, :, 0]

    eosin = separated_image[:, :, 1]

    return hematoxylin, eosin
コード例 #13
0
def get_dye_separation(img_dict, color="H"):
    '''
    Arguments:
        ihc_rgb is a dictionary of color images
        color = "H" (hematoxylin) or "E" Eosin
    Returns:
        dictionary of greyscale 2D images, separated by main dye colors into H or E component
    rgb2hed is RGB to Haematoxylin-Eosin-DAB (HED) color space conversion.    
    '''
    d = {}
    for k, v in img_dict.items():
        if color == "H":
            d[k] = rgb2hed(v)[:, :, 0]
        else:
            d[k] = rgb2hed(v)[:, :, 1]
    return d
コード例 #14
0
ファイル: utils.py プロジェクト: ericwdanielson/DSB-2018
    def load_image3(self, image_id):
        image = skimage.io.imread(image_id)
        if image.shape[2] == 4:
            image = image[:, :, 0:3]

        if (image[:, :, 0] == image[:, :,
                                    1]).all() == False:  #is a color image
            ihc_hed = rgb2hed(image)
            h = rescale_intensity(ihc_hed[:, :, 0], out_range=(0, 255))
            image[:, :, 0] = h
            image[:, :, 1] = h
            image[:, :, 2] = h
            image = image.astype('uint8')
        blur_size = 1
        unsharp_strength = 0.8
        float_image = img_as_float(image) * 255
        blurred = filters.gaussian(float_image,
                                   blur_size,
                                   preserve_range=True,
                                   multichannel=True)
        highpass = float_image - unsharp_strength * blurred
        sharp = float_image + highpass
        sharp = sharp / np.max(sharp) * 255

        return sharp.astype('uint8')
コード例 #15
0
def run(original_image_path):

    outputPathList = []

    # Read original image
    ihc_rgb = io.imread(original_image_path)

    # Process
    ihc_hed = rgb2hed(ihc_rgb)
    ihc_h = exposure.rescale_intensity(ihc_hed[:, :, 0], out_range=(0, 255))
    ihc_e = exposure.rescale_intensity(ihc_hed[:, :, 1], out_range=(0, 255))
    ihc_d = exposure.rescale_intensity(ihc_hed[:, :, 2], out_range=(0, 255))

    images = [ihc_h, ihc_e, ihc_d]
    outnames = ['Hematoxylin.tiff', 'Eosin.tiff', 'DAB.tiff']

    for img, out in zip(images, outnames):

        outputPathList.append(out)
        tf.imwrite(out, np.int16(img))

    tf.imwrite('HED.tiff', np.float16(ihc_hed))
    outputPathList.append('HED.tiff')

    print(outputPathList)

    # Return apeer output values as dictionary
    return {'processed_images': outputPathList}
コード例 #16
0
def color_deconv(img):
    hed = rgb2hed(img)
    h = rescale_intensity(hed[:, :, 0], out_range=(0, 255))
    # zdh = np.dstack((np.zeros_like(h),h,h))
    h = np.expand_dims(h, axis=-1)
    zdh = np.repeat(h, 3, axis=-1)
    return zdh
コード例 #17
0
def check_color_conv():
    data = dataset.UVectorNetDataset(fold=-1,
                                     batch_size=1,
                                     output_watershed=True,
                                     use_colors=False)

    from skimage.color import rgb2hed
    import skimage.exposure
    import PIL.Image

    for sample_id, img in data.images.items():
        print(sample_id)
        fn = '/home/dmytro/ml/kaggle/2018_data_science_bowl/input/stage1_test/0f1f896d9ae5a04752d3239c690402c022db4d72c0d2c087d73380896f72c466/images/0f1f896d9ae5a04752d3239c690402c022db4d72c0d2c087d73380896f72c466.png'
        img = PIL.Image.open(fn)
        img = np.array(img)[:, :, :3]

        plt.subplot(1, 3, 1)
        utils.print_stats('img', img)
        plt.imshow(img)

        plt.subplot(1, 3, 2)
        preprocessed = data.preprocess(img)[:, :, 0]
        utils.print_stats('preprocessed', preprocessed)
        plt.imshow(preprocessed)

        plt.subplot(1, 3, 3)
        img_hed = rgb2hed(img / 255.0 * 2 - 1)[:, :, 0]
        utils.print_stats('img_hed', img_hed)
        # hed_scaled = skimage.exposure.rescale_intensity(img_hed[:, :, 0]*-1, out_range=(0.0, 1.0))
        # utils.print_stats('img_hed_scaled', img_hed)
        plt.imshow(img_hed * -1)

        plt.show()
コード例 #18
0
def color_aug(img):
    adj_add = np.array([[[0.02, 0.001, 0.15]]], dtype=np.float32)
    img2 = np.clip(
        hed2rgb(
            rgb2hed(img.transpose((1, 0, 2)) / 255.0) +
            np.random.uniform(-1.0, 1.0, (1, 1, 3)) * adj_add).transpose(
                (1, 0, 2)) * 255.0, 0.0, 255.0)
    return img2.astype(np.uint8)
コード例 #19
0
 def stain_aug(self, image, k=0.03):
     # input must be rgb
     hed_image = rgb2hed(image)
     w = 1 - k + np.random.rand(3) * k * 2
     b = -k + np.random.rand(3) * k * 2
     for i in range(3):
         hed_image[:, :, i] = w[i] * hed_image[:, :, i] + b[i]
     return (hed2rgb(hed_image) * 255).astype(np.uint8)
コード例 #20
0
ファイル: augs.py プロジェクト: nsh23/hover_fork
 def _augment(self, img, s):
     alpha = [0.95, 1.05]
     bias = [-0.01,  0.01] # -0.05,  0.05
     hed_img = rgb2hed(img)
     for channel in range(3):
         hed_img[..., channel] *= random.choice(np.arange(alpha[0], alpha[1], 0.01))
         hed_img[..., channel] += random.choice(np.arange(bias[0], bias[1], 0.01))
     return img_as_ubyte(hed2rgb(hed_img))
コード例 #21
0
def main():

    files = []
    for file in os.listdir('images'):
        # print('{}'.format(os.path.join(os.getcwd(), 'images', file)))
        files.append('{}'.format(os.path.join(os.getcwd(), 'images', file)))

    fig, axs = plt.subplots(2, 3)

    black = Image.new('RGB', (400, 400), 'black')

    for (f, i, ax) in zip(files, range(6), axs.ravel()):

        # Read image
        im = io.imread(f)

        # Resize image
        im = skimage.transform.resize(im, (400, 400), anti_aliasing=True)

        # Color conversion
        im_hed = rgb2hed(im)

        # Rescale colors to (0..1) and stack it to list
        h = exposure.rescale_intensity(im_hed[:, :, 0], out_range=(0, 1))
        d = exposure.rescale_intensity(im_hed[:, :, 2], out_range=(0, 1))
        zdh = np.dstack((np.zeros_like(h), d, h))

        # To grayscale
        gray = rgb2gray(zdh)
        # plt.imshow(gray)

        # Get factor of brightness threshold
        thresh = threshold_otsu(gray)

        # Transform to binary image
        im_bin = gray > thresh

        # Apply dilatation
        im_bin = morphology.dilation(im_bin, morphology.square(5))

        # Remove small objects
        im_bin = morphology.remove_small_objects(im_bin)

        # Find contours
        contour = measure.find_contours(im_bin, 0.8)

        # Plot all contours found and add circle in the centre
        for n, c in enumerate(contour):
            if (len(c) > 100):
                ax.plot(c[:, 1], c[:, 0], linewidth=1, color='white')

        ax.imshow(black, interpolation='nearest', cmap=plt.cm.gray)

        ax.axis('image')
        ax.set_xticks([])
        ax.set_yticks([])

    plt.show()
コード例 #22
0
def preprocess(image,
               crop_size,
               color_augmentation=False,
               rotate=False,
               hed=False,
               nocrop=False):
    """
    :param image: PIL image
    :param image_size: size of the image
    :param crop_size: size of the processed image
    :param rotate: if True, rotate image as Data Augmentation
    :param color_augmentation: if True, perturb images with tensorflow
    :param hed: if True, transfer to hed space
    :param nocrop: if True, no cropping
    :param divide: it True, divide 255
    :return:
    """

    # color augmentation
    if color_augmentation:
        image = color_aug(image)

    # rotation (degree, not radian)
    if rotate:
        r = np.random.choice(
            [0, Image.ROTATE_90, Image.ROTATE_180, Image.ROTATE_270])
        image = image.transpose(r) if r > 0 else image

    image = np.asarray(image)

    # rgb2hed
    if hed:
        image = rgb2hed(image)

    # transpose
    image = image[:, :, ::-1].astype('float32')
    image -= np.array([104.0, 117.0, 123.0], dtype=np.float32)  # BGR
    image = image.transpose((2, 0, 1))

    # crop
    if not nocrop:
        crop_size = crop_size
        _, h, w = image.shape
        if random:
            # Randomly crop a region and flip the image
            top = random.randint(0, h - crop_size - 1)
            left = random.randint(0, w - crop_size - 1)
            if random.randint(0, 1):
                image = image[:, :, ::-1]
        else:
            # Crop the center
            top = (h - crop_size) // 2
            left = (w - crop_size) // 2
        bottom = top + crop_size
        right = left + crop_size
        image = image[:, top:bottom, left:right]

    return image
コード例 #23
0
def Color_Deconvolution(Img, Channel):
    # Channel 0 -> Hema
    # Channel 1 -> Eosin
    # Channel 2 -> DAB
    Img = rgb2hed(Img)
    Img = Img[:, :, Channel]
    Img = rescale_intensity(Img, out_range=(0, 1))
    Img = np.uint8(Img * 255)
    return Img
コード例 #24
0
def imagetoDAB(image):
    image_hed = rgb2hed(image)
    d = image_hed[:, :, 2]
    img_dab = np.zeros_like(image)
    img_dab[:, :, 0] = d
    img_dab[:, :, 1] = d
    img_dab[:, :, 2] = d

    return img_dab
コード例 #25
0
def random_hed_ratio(img,
                     bias_range=0.025,
                     coef_range=0.025,
                     random_state=None):
    rstate = check_random_state(random_state)
    hed = rgb2hed(img)
    bias = rstate.uniform(-bias_range, bias_range, 3)
    coefs = rstate.uniform(1 - coef_range, 1 + coef_range, 3)
    return np.clip(hed2rgb(hed * coefs + bias), 0, 1)
コード例 #26
0
def dab(im, pr1, returnRGB = False):
    #input:     - im: image 
    #           - pr1: procentage with which intensity levels should be increased
    #output:    - dab image
    ihc_hed = color.rgb2hed(im)
    pr2 = 100-pr1
    d = rescale_intensity(ihc_hed[:, :, 2], out_range=(0, 1))
    p1, p2 = np.percentile(d, (pr1, pr2))
    d = exposure.rescale_intensity(d,in_range=(p1, p2))
    return d
コード例 #27
0
def dye_color_separation(ihc_rgb, channel=None):
    '''
    Arguments:
        ihc_rgb is a color image in a numpy array, 3D
        channel (optiona) If set to "H" or "E" returns only the hetatoxylin or eosin channel as greyscale, else, channel separated 3D
    Returns:

    '''
    ihc_hed = rgb2hed(ihc_rgb)
    return ihc_hed
コード例 #28
0
def color_deconvolution(_img, channel):
    # Channel 0 -> Hema
    # Channel 1 -> Eosin
    # Channel 2 -> DAB
    _img = rgb2hed(_img)
    _img = _img[:, :, channel]
    _img = rescale_intensity(_img, out_range=(0, 1))
    # Img = 1-Img
    _img = np.uint8(_img * 255)
    return _img
コード例 #29
0
def show_custom_channels(img, color_space, title=''):
    """Show image with color space of choice

    Args:
        img: the input image
        color_space: color space to show images, either `rgb` or `hed`
        title: title for the plot (optional)

    Returns:
        list of corresponding channels
    """
    assert color_space in ['rgb', 'hed'], \
            'Unsupported color space. Must be either `rgb` or `hed`'

    if color_space == 'rgb':
        # allocate memory for 3 channels
        r_chn = np.zeros(img.shape, dtype=np.uint8)
        g_chn = np.zeros(img.shape, dtype=np.uint8)
        b_chn = np.zeros(img.shape, dtype=np.uint8)

        # extract data from each channel
        r_chn[..., 0] = img[..., 0]
        g_chn[..., 1] = img[..., 1]
        b_chn[..., 2] = img[..., 2]

        img_lst = [img, r_chn, g_chn, b_chn]
        cmap_lst = [None, None, None, None]
        title_lst = ['Original image', 'R channel', 'G channel', 'B channel']
    elif color_space == 'hed':
        # Create an artificial color close to the orginal one
        cmap_hema = LinearSegmentedColormap.from_list('mycmap', ['white', 'navy'])
        cmap_dab = LinearSegmentedColormap.from_list('mycmap', ['white',
                                                     'saddlebrown'])
        cmap_eosin = LinearSegmentedColormap.from_list('mycmap', ['darkviolet',
                                                       'white'])

        hed = color.rgb2hed(img)

        img_lst = [img, hed[..., 0], hed[..., 1], hed[..., 2]]
        cmap_lst = [None, cmap_hema, cmap_eosin, cmap_dab]
        title_lst = ['Original image', 'Hematoxylin', 'Eosin', 'DAB']

    # plot the original image and its 3 channels
    fig, axes = plt.subplots(1, 4, figsize=(16, 4), sharex=True, sharey=True)
    for i in range(4):
        axes[i].imshow(img_lst[i], cmap_lst[i])
        axes[i].set_title(title_lst[i])
        axes[i].axis('off')

    plt.suptitle(title)

    # return color channels and color maps if using hed
    if color_space == 'hed':
        return img_lst[1:], cmap_lst[1:]
    return None
コード例 #30
0
 def he_aug(result):
     hed = rgb2hed(np.clip(result.transpose(1, 2, 0), -1.0,
                           1.0))
     ah = 0.95 + random.random() * 0.1
     bh = -0.05 + random.random() * 0.1
     ae = 0.95 + random.random() * 0.1
     be = -0.05 + random.random() * 0.1
     hed[:, :, 0] = ah * hed[:, :, 0] + bh
     hed[:, :, 1] = ae * hed[:, :, 1] + be
     result = hed2rgb(hed).transpose(2, 0, 1)
     return result
コード例 #31
0
def dye_color_separation_dict(img_dict):
    '''
    Arguments:
        img_dict is a dictionary of images to dye color separate 
    returns 
        img_dict of images separated into the primary dye colors for HE and DAG
    '''
    d = {}
    for k, v in img_dict.items():
        d[k] = rgb2hed(v)
    return d
コード例 #32
0
ファイル: image-filters.py プロジェクト: v-ilin/py-scripts
def add_filters_to_img(destination_images_dir, img_path, img_name, annotations,
                       destination_dict):
    base, extension = os.path.splitext(img_name)

    img_rgb = io.imread(img_path)
    img_hed = rgb2hed(img_rgb)

    f1_filepath = get_destination_img_path(destination_images_dir, 1, base,
                                           extension)
    io.imsave(f1_filepath, rgb2gray(img_rgb))

    img_entity, img_annotations = get_img_annotations(img_name, annotations)

    copy_instance_annotations(img_entity, img_annotations,
                              base + "_f1" + extension, destination_dict)

    # Rescale hematoxylin and DAB signals and give them a fluorescence look
    h = rescale_intensity(img_hed[:, :, 0], out_range=(0, 1))
    d = rescale_intensity(img_hed[:, :, 2], out_range=(0, 1))

    zdh = np.dstack((np.zeros_like(h), d, h))
    f2_filepath = get_destination_img_path(destination_images_dir, 2, base,
                                           extension)
    io.imsave(f2_filepath, zdh)

    copy_instance_annotations(img_entity, img_annotations,
                              base + "_f2" + extension, destination_dict)

    zdh = np.dstack((np.zeros_like(h), d, d))
    f3_filepath = get_destination_img_path(destination_images_dir, 3, base,
                                           extension)
    io.imsave(f3_filepath, zdh)

    copy_instance_annotations(img_entity, img_annotations,
                              base + "_f3" + extension, destination_dict)

    zdh = np.dstack((np.zeros_like(h), h, h))
    f4_filepath = get_destination_img_path(destination_images_dir, 4, base,
                                           extension)
    io.imsave(f4_filepath, zdh)

    copy_instance_annotations(img_entity, img_annotations,
                              base + "_f4" + extension, destination_dict)

    f5_filepath = get_destination_img_path(destination_images_dir, 5, base,
                                           extension)
    io.imsave(
        f5_filepath,
        util.random_noise(img_rgb[:, :, :3],
                          mode="salt",
                          amount=random.uniform(0.05, 0.15)))

    copy_instance_annotations(img_entity, img_annotations,
                              base + "_f5" + extension, destination_dict)
コード例 #33
0
    def run(self, image):
        assert image.size > 0
        hed = cv2.split(rgb2hed(image))[1]
        hed = img_as_ubyte(1.0 - hed)
        # hed = 1.0 - hed
        hed = rescale_intensity(hed)
        im = hed
        # im = img_as_ubyte(hed)
        # com.debug_im(im)
        im[im >= 115] = 255
        im[im < 115] = 0
        im = rank.enhance_contrast(im, disk(5))
        im = morph.close(im, disk(3))

        can = cv2.adaptiveBilateralFilter(im,
                                          self.bilateral_kernel,
                                          self.sigma_color)
        return can
コード例 #34
0
def salvarcombinacoes(img):
    img_rgb = color.convert_colorspace(img, 'RGB', 'RGB')
    img_hsv = color.convert_colorspace(img_rgb, 'RGB', 'HSV')
    img_lab = color.rgb2lab(img_rgb)
    img_hed = color.rgb2hed(img_rgb)
    img_luv = color.rgb2luv(img_rgb)
    img_rgb_cie = color.convert_colorspace(img_rgb, 'RGB', 'RGB CIE')
    img_xyz = color.rgb2xyz(img_rgb)
    img_cmy = rgb2cmy(img_rgb)

    lista = [img_rgb, img_hsv, img_lab, img_hed, img_luv, img_rgb_cie, img_xyz, img_cmy]
    lista2 = ["rgb", "hsv", "lab", "hed", "luv", "rgb_cie", "xyz", "cmy"]
    for i in range(len(lista)):
        for j in range(len(lista)):
            for k in range(3):
                for l in range(3):
                    nome = lista2[i] + str(k) + lista2[j] + str(l) + ".jpg"
                    io.imsave(nome, juntarcanais(lista[i][:, :,k], lista[j][:, :, l]), )

    return
コード例 #35
0
    def _apply_(self, *image):
        res = ()
        n_img = 0
        for img in image:
            if n_img == 0:

                dec_img = color.rgb2hed(img)
                ### perturbe each channel H, E, Dab
                for i in range(3):
                    k_i = self.params['k'][i]
                    b_i = self.params['b'][i]
                    dec_img[:,:,i] = GreyValuePerturbation(dec_img[:, :, i], k_i, b_i)
                sub_res = color.hed2rgb(dec_img).astype('uint8')

                ### Have to implement deconvolution of the deconvolution


            else:
                sub_res = img

            res += (sub_res,)
            n_img += 1
        return res
コード例 #36
0
def processhed(imagefile, algorithm):
    """Process images with different algorithms"""
    image = plt.imread(StringIO.StringIO(imagefile), format="JPG")

    ihc_hed = rgb2hed(image)

    if algorithm == '01':
        result = plt.cm.gray(rescale_intensity(ihc_hed[:, :, 0],
                                               out_range=(0, 1)))
    elif algorithm == '02':
        result = plt.cm.gray(rescale_intensity(ihc_hed[:, :, 1],
                                               out_range=(0, 1)))
    elif algorithm == '03':
        result = plt.cm.gray(rescale_intensity(ihc_hed[:, :, 2],
                                               out_range=(0, 1)))
    else:
        result = image

    output = StringIO.StringIO()
    plt.imsave(output, result, format="PNG")
    contents = output.getvalue()
    output.close()

    return contents
コード例 #37
0
ファイル: test_colorconv.py プロジェクト: AceHao/scikit-image
 def test_hed_rgb_float_roundtrip(self):
     img_rgb = img_as_float(self.img_rgb)
     assert_array_almost_equal(hed2rgb(rgb2hed(img_rgb)), img_rgb)
コード例 #38
0
ファイル: test_colorconv.py プロジェクト: AceHao/scikit-image
 def test_hed_rgb_roundtrip(self):
     img_rgb = img_as_ubyte(self.img_rgb)
     with expected_warnings(['precision loss']):
         new = img_as_ubyte(hed2rgb(rgb2hed(img_rgb)))
     assert_equal(new, img_rgb)
コード例 #39
0
from skimage.feature import blob_log
from pylab import uint8
from skimage.filter import threshold_otsu
from skimage import img_as_ubyte #Conversão
from PIL import Image
from skimage.morphology import disk
from skimage.color import rgb2hed
from skimage.measure import label, regionprops 

print __doc__

glom_rgb = Image.open('s3.jpg')
glom_gl = glom_rgb.convert('L') #Gray Level

glom_hed = rgb2hed(glom_rgb) #hed
glom_h =  glom_hed[:, :, 0] #hematoxylim
glom_h = ia.ianormalize(glom_h)
selem = disk(10) #elemento estruturante
glom_h = np.array(glom_h) 
glom_h = 255 - uint8(glom_h)

#Segmentation
glom_by_reconsTopHat = morph.closerecth(glom_h,selem) #reconstrução morfológicas de fechamento

global_thresh = threshold_otsu(glom_by_reconsTopHat) #Otsu
glom_bin = glom_by_reconsTopHat > global_thresh + global_thresh*0.1 
glom_bin = img_as_ubyte(glom_bin)
selem = disk(3)    
glom_seg = morph.open(glom_bin, selem)
glom_seg = morph.close(glom_seg, selem) #Fechamento final
コード例 #40
0
    ax1.axis("off")
    ax2.axis("off")

    return plt

#Input's Block

    #Single Reader
img = data.imread('img/nor.jpg', False,)
    #Set Reader

#Convert Block
img_rgb = color.convert_colorspace(img, 'RGB', 'RGB') #No need
img_hsv = color.convert_colorspace(img_rgb, 'RGB', 'HSV')
img_lab = color.rgb2lab(img_rgb)
img_hed = color.rgb2hed(img_rgb)
img_luv = color.rgb2luv(img_rgb)
img_rgb_cie = color.convert_colorspace(img_rgb, 'RGB', 'RGB CIE')
img_xyz = color.rgb2xyz(img_rgb)

#Save Test Block
"""io.imsave("image_hsv.jpg", img_hsv, )
io.imsave("image_lab.jpg", img_lab, )
io.imsave("image_hed.jpg", img_hed, )
io.imsave("image_luv.jpg", img_luv, )
io.imsave("image_rgb_cie.jpg", img_rgb_cie, )
io.imsave("image_xyz.jpg", img_xyz, )
"""
#Layers Block
"""
canalExtration(img_rgb, "RGB").show()
コード例 #41
0
    def getBinaryImage(self):
        self.ploting = False
        HEDAB = rgb2hed(self.image)
        R = self.image[:, :, 0]
        G = self.image[:, :, 1]
        B = self.image[:, :, 2]
        H = HEDAB[:, :, 0]
        E = HEDAB[:, :, 1]
        DAB = HEDAB[:, :, 2]
        BR = B * 2 / ((1 + R + G) * (1 + B + R + G))  # Blue-ratio image
        V = self.getV()  # From HSV
        (L, L2) = self.getL()  # From CIELAB and CIELUV
        BRSmoothed = ndimage.gaussian_filter(BR, 1)
        LSmoothed = ndimage.gaussian_filter(L, 1)
        VSmoothed = ndimage.gaussian_filter(V, 1)
        HSmoothed = ndimage.gaussian_filter(H, 1)
        ESmoothed = ndimage.gaussian_filter(E, 1)
        RSmoothed = ndimage.gaussian_filter(R, 1)
        DABSmoothed = ndimage.gaussian_filter(DAB, 1)
        imLLog = self.filterImage(gaussian_laplace(LSmoothed, 9), 85) == False
        imVLog = self.filterImage(gaussian_laplace(VSmoothed, 9), 85) == False
        imELog = self.filterImage(gaussian_laplace(ESmoothed, 9), 84) == False
        imRLog = self.filterImage(gaussian_laplace(RSmoothed, 9), 84) == False
        imDABLog = self.filterImage(gaussian_laplace(DABSmoothed, 9), 50)
        imHLog = self.filterImage(gaussian_laplace(HSmoothed, 9), 8)
        imLog = self.filterImage(gaussian_laplace(BRSmoothed, 9), 9)
        imR = self.filterImage(R, 2.5)
        imB = self.filterImage(B, 10.5)
        imV = self.filterImage(V, 6.5)
        imL = self.filterImage(L, 2.5)
        imL2 = self.filterImage(L2, 2.5)
        imE = self.filterImage(E, 18)
        imH = self.filterImage(H, 95) == False
        imDAB = self.filterImage(DAB, 55) == False
        imBR = self.filterImage(BR, 63) == False
        binaryImg = (
            imR
            & imV
            & imB
            & imL
            & imL2
            & imE
            & imH
            & imDAB
            & imLog
            & imBR
            & imLLog
            & imVLog
            & imELog
            & imHLog
            & imRLog
            & imDABLog
        )
        openImg = ndimage.binary_opening(binaryImg, iterations=2)
        closedImg = ndimage.binary_closing(openImg, iterations=8)
        if self.ploting:
            plt.imshow(self.image)
            plt.show()
            plt.imshow(imR)
            plt.show()
            plt.imshow(imV)
            plt.show()
            plt.imshow(imB)
            plt.show()
            plt.imshow(imL)
            plt.show()
            plt.imshow(closedImg)
            plt.show()

        BRVL = np.zeros(self.image.shape)
        BRVL[:, :, 0] = BR
        BRVL[:, :, 1] = V
        BRVL[:, :, 2] = L / rangeL
        # ResizeHEDAB, from 0 to 1.
        HEDAB[:, :, 0] = (H - minH) / rangeH
        HEDAB[:, :, 1] = (E - minE) / rangeE
        HEDAB[:, :, 2] = (DAB - minDAB) / rangeDAB

        return (
            BinaryImageWorker(closedImg, self.rows, self.columns),
            RGBImageWorker(HEDAB, self.rows, self.columns),
            RGBImageWorker(BRVL, self.rows, self.columns),
            BinaryImageWorker(binaryImg, self.rows, self.columns),
        )
コード例 #42
0
"""
import matplotlib.pyplot as plt

from skimage import data
from skimage.color import rgb2hed
from matplotlib.colors import LinearSegmentedColormap

# Create an artificial color close to the original one
cmap_hema = LinearSegmentedColormap.from_list('mycmap', ['white', 'navy'])
cmap_dab = LinearSegmentedColormap.from_list('mycmap', ['white',
                                             'saddlebrown'])
cmap_eosin = LinearSegmentedColormap.from_list('mycmap', ['darkviolet',
                                               'white'])

ihc_rgb = data.immunohistochemistry()
ihc_hed = rgb2hed(ihc_rgb)

fig, axes = plt.subplots(2, 2, figsize=(7, 6), sharex=True, sharey=True)
ax = axes.ravel()

ax[0].imshow(ihc_rgb)
ax[0].set_title("Original image")

ax[1].imshow(ihc_hed[:, :, 0], cmap=cmap_hema)
ax[1].set_title("Hematoxylin")

ax[2].imshow(ihc_hed[:, :, 1], cmap=cmap_eosin)
ax[2].set_title("Eosin")

ax[3].imshow(ihc_hed[:, :, 2], cmap=cmap_dab)
ax[3].set_title("DAB")
コード例 #43
0
data = []

for img in files:
    label = img[-5:-4]
    labels.append(float(label))
    image = cv2.imread(img, flags=1)
    canny, gray = preprocessor.run(image)
    # com.debug_im(image)
    conts = segment.run(canny, gray, image)
    try:
        max_cont = max(conts, key=lambda x: x.area)
    except ValueError:
        print "filename: ", img
        exit()
    # com.debug_im(max_cont.get_region(rgb2hed(image)[1]))
    region = max_cont.get_region(cv2.split(rgb2hed(image))[1])
    # com.debug_im(region)
    max_cont = cv2.resize(region, (30, 30)).flatten()
    data.append(max_cont)

data_train, data_test, labels_train, labels_test = train_test_split(
    data, labels, test_size=0.25)
print "test size: ", len(data_test)
print "train size: ", len(data_train)

# Randomized PCA
components_range = range(2, 300, 6)

scores = []
for n_components in components_range:
    # pca = SparsePCA(n_components, n_jobs=-1).fit(data_train)
コード例 #44
0
ファイル: test_colorconv.py プロジェクト: A-0-/scikit-image
 def test_hed_rgb_roundtrip(self):
     img_rgb = img_as_ubyte(self.img_rgb)
     assert_equal(img_as_ubyte(hed2rgb(rgb2hed(img_rgb))), img_rgb)
コード例 #45
0
from mahotas.features import texture, zernike_moments
import pywt
from scipy.stats.stats import skew, kurtosis
from Tamura import Tamura
from scipy.stats.mstats_basic import mquantiles

"""
    Constant for L resizing
"""
rangeL = (1.0 / 0.95047) * 116.0 - 16.0

"""
    Constants for HEDAB resizing
"""
imageTest = np.array([[[255, 0, 0]]], dtype=np.uint8)
minH = rgb2hed(imageTest)[0][0][0]
imageTest = np.array([[[0, 255, 255]]], dtype=np.uint8)
maxH = rgb2hed(imageTest)[0][0][0]
rangeH = maxH - minH
imageTest = np.array([[[0, 255, 0]]], dtype=np.uint8)
minE = rgb2hed(imageTest)[0][0][1]
imageTest = np.array([[[255, 0, 255]]], dtype=np.uint8)
maxE = rgb2hed(imageTest)[0][0][1]
rangeE = maxE - minE
imageTest = np.array([[[0, 0, 255]]], dtype=np.uint8)
minDAB = rgb2hed(imageTest)[0][0][2]
imageTest = np.array([[[255, 255, 0]]], dtype=np.uint8)
maxDAB = rgb2hed(imageTest)[0][0][2]
rangeDAB = maxDAB - minDAB

"""
コード例 #46
0
import matplotlib.pyplot as plt
from skimage.color import rgb2hed
import cv2
import numpy as np
import sys

print("python: ",str(sys.argv[1]))
img = cv2.imread(str(sys.argv[1]),1)
#img = cv2.imread("Training Data/A03/frames/x40/A03_00Aa.tiff",1)
#img = cv2.pyrDown(img)
ihc_hed = rgb2hed(img)

min,max,minLoc,maxLoc = cv2.minMaxLoc(ihc_hed[:,:,2])
print min,max

ihc_hed = np.array(ihc_hed,dtype = 'float32');
ret,thresh = cv2.threshold(ihc_hed[:,:,2],min+(max-min)*0.5,255,cv2.THRESH_BINARY);
#thresh = ihc_hed[:,:,2]
#ret = 0
kernelSize = 5
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(kernelSize,kernelSize))
#thresh = cv2.erode(thresh,kernel,iterations=2)
#thresh = cv2.dilate(thresh,kernel,iterations=2)
#thresh = cv2.morphologyEx(thresh,cv2.MORPH_OPEN,kernel, iterations=1)
thresh = cv2.convertScaleAbs(thresh);thresh = cv2.medianBlur(thresh,9)
#print ret

#cv2.imshow("1",thresh)
cv2.imwrite(sys.argv[2],thresh)
#cv2.waitKey(0)
コード例 #47
0
ファイル: eigencell.py プロジェクト: dangkhoasdc/CellCounter
    filename = "allidb2.txt"

files = []

with open(filename, "r") as f:
    files = [line.strip() for line in f.readlines()]

# Create samples and its label
labels = []
data = []

for img in files:
    label = img[-5:-4]
    labels.append(float(label))
    image = cv2.imread(img, flags=1)
    image = cv2.split(rgb2hed(image))[1]
    image = cv2.resize(image, (40, 40))
    data.append(image.flatten())

data_train, data_test, labels_train, labels_test = train_test_split(
    data, labels, test_size=0.25)
print "test size: ", len(data_test)
print "train size: ", len(data_train)
data_train = np.array(data_train)
# data_train = np.transpose(data_train)
data_test = np.array(data_test)
# data_test = np.transpose(data_test)
# Randomized PCA
n_components = 400
# pca = SparsePCA(n_components, n_jobs=-1).fit(data_train)
# pca = RandomizedPCA(n_components, whiten=True).fit(data_train)