Example #1
0
def _otsu(data: torch.Tensor, **kwargs):
    """
    Use Otsu's method, which assumes a GMM with 2 components
    but uses some heuristic to maximize the variance differences.
    """
    h = 2 ** int(1 + math.log2(data.shape[0]) / 2)
    fake_img = data.view(h, -1).cpu().numpy()
    return otsu(fake_img, h)
Example #2
0
def median_otsu(mean_b0, median_radius=4, numpass=2, dilate=1):

    mask = multi_median(mean_b0.eval(), median_radius, numpass)

    thresh = tf.constant(otsu(mask))
    mask = tf.constant(mask) > tf.to_float(thresh)

    for _ in range(dilate):
        mask = dilation(mask)

    return tf.squeeze(mask)
def imagen_auto_segmentada(prom_masDesvEstandar,
                           prom_menosDesvEstandar,
                           pintar=True):
    imagen_auto1 = np.zeros((230, 350), dtype="float64")
    imagen_auto2 = np.zeros((230, 350), dtype="float64")
    cap = cv.VideoCapture("Videos/Personas.mp4")

    while (cap.isOpened()):
        ret, frame = cap.read()
        if (not ret):
            break
        gray = cv.cvtColor(frame, cv.COLOR_RGBA2GRAY)

        gray = gray[200:430, 500:850]
        imagen_auto1 = gray < prom_menosDesvEstandar
        imagen_auto2 = gray > prom_masDesvEstandar
        imagen_or = np.bitwise_or(
            imagen_auto1, imagen_auto2)  #func_or(imagen_auto1,imagen_auto2)
        s = 10
        w = 3
        t = (((w - 1) / 2) - 0.5) / s
        imagen_filtrada = gaussian(imagen_or, sigma=s, truncate=t)
        umbral = otsu(imagen_filtrada)
        imagen_filtrada = imagen_filtrada > umbral
        imagen_filtrada = median(imagen_or, np.ones((5, 5)))

        num_pixeles = np.sum(imagen_filtrada) / 255
        num_personas = num_pixeles / 1200
        num_personas_t = round(num_personas)
        #num_ceil = ceil(num_personas)
        #num_floor = floor(num_personas)
        print("Num pixeles = {pixeles} Num personas = {personas} ceil={trun}".
              format(pixeles=num_pixeles,
                     personas=num_personas,
                     trun=num_personas_t))
        imagen_resultante = gray * imagen_filtrada
        cv.imshow("Imagen segmentada binaria", imagen_filtrada)
        cv.imshow("Video segmentado", imagen_resultante)
        cv.imshow("Video leido", frame)
        #time.sleep(.20)
        if (cv.waitKey(0) & 0xff == ord("q")):
            break
        #time.sleep(.20)
    cap.release()
    cv.destroyAllWindows()
def _otsu(data: torch.Tensor, **kwargs) -> float:
    """
    Returns an intensity threshold for an image that separates it
    into backgorund and foreground pixels.

    The implementation uses Otsu's method, which assumes a GMM with
    2 components but uses some heuristic to maximize the variance
    differences. The input data is shaped into a 2D image for the
    purpose of evaluating the threshold value.

    Args:
        data: Pytorch tensor containing the data.

    Returns:
        Threshold value determined via Otsu's method.
    """
    h = 2**int(1 + math.log2(data.shape[0]) / 2)
    fake_img = data.view(h, -1).cpu().numpy()
    return otsu(fake_img, h)
Example #5
0
def otsu_filter(dataset_to_filter: np.array):
    dataset_shape_entries_pos = 0
    img_entries = dataset_to_filter.shape[dataset_shape_entries_pos]
    img_height = 32
    img_width = 32
    dataset_filtered_shape = (img_entries, img_height, img_width,\
    greyscaled_colour_channels)
    dataset_filtered = np.empty(dataset_filtered_shape)
    cur_img = 0
    for data in dataset_to_filter:
        # fromarray gives a too many dimensions error with
        # image colour channels included.
        otsu_mask = otsu(data)
        image_filtered = data < otsu_mask
        image_filtered = image_filtered.astype(np.float32)
        # resize to ensure image array shape correct.
        image_filtered = image_filtered.reshape((img_height, \
            img_width, greyscaled_colour_channels))

        dataset_filtered[cur_img] = image_filtered

        cur_img += 1

    return dataset_filtered
Example #6
0
        image_2 = cv.imread("Personas/segmentacion/programa/%d.jpg" % indice,
                            cv.IMREAD_GRAYSCALE)
        image_3 = cv.imread("Personas/segmentacion/programa_2/%d.jpg" % indice,
                            cv.IMREAD_GRAYSCALE)

        image_1 = image_1[30:250, 85:435]
        image_2 = image_2[40:247, 55:388]
        image_3 = image_3[40:247, 55:388]

        image_1 = tr.resize(image_1, (220, 360), mode='constant')
        image_2 = tr.resize(
            image_2, (220, 360),
            mode='constant')  #tr.resize() Aplica un escalamiento a la imagen
        image_3 = tr.resize(image_3, (220, 360), mode='constant')

        umbral1 = otsu(image_1)
        umbral2 = otsu(image_2)
        umbral3 = otsu(image_3)
        """
        plt.title("Segmentada Manual {indice}".format(indice=indice))
        plt.imshow(image_1,cmap="gray")
        plt.show()
        
        plt.title("Segmentada Programa {indice}".format(indice=indice))
        plt.imshow(image_2,cmap="gray")
        plt.show()
        
        plt.title("Segmentada Programa_2 {indice}".format(indice=indice))
        plt.imshow(image_3,cmap="gray")
        plt.show()
        
Example #7
0
def median_otsu(input_volume, median_radius=4, numpass=4,
                autocrop=False, vol_idx=None, dilate=None):
    """Simple brain extraction tool method for images from DWI data.

    It uses a median filter smoothing of the input_volumes `vol_idx` and an
    automatic histogram Otsu thresholding technique, hence the name
    *median_otsu*.

    This function is inspired from Mrtrix's bet which has default values
    ``median_radius=3``, ``numpass=2``. However, from tests on multiple 1.5T
    and 3T data     from GE, Philips, Siemens, the most robust choice is
    ``median_radius=4``, ``numpass=4``.

    Parameters
    ----------
    input_volume : ndarray
        ndarray of the brain volume
    median_radius : int
        Radius (in voxels) of the applied median filter (default: 4).
    numpass: int
        Number of pass of the median filter (default: 4).
    autocrop: bool, optional
        if True, the masked input_volume will also be cropped using the
        bounding box defined by the masked data. Should be on if DWI is
        upsampled to 1x1x1 resolution. (default: False).
    vol_idx : None or array, optional
        1D array representing indices of ``axis=3`` of a 4D `input_volume` None
        (the default) corresponds to ``(0,)`` (assumes first volume in
        4D array).

    dilate : None or int, optional
        number of iterations for binary dilation

    Returns
    -------
    maskedvolume : ndarray
        Masked input_volume
    mask : 3D ndarray
        The binary brain mask

    Notes
    -----
    Copyright (C) 2011, the scikit-image team
    All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are
    met:

     1. Redistributions of source code must retain the above copyright
        notice, this list of conditions and the following disclaimer.
     2. Redistributions in binary form must reproduce the above copyright
        notice, this list of conditions and the following disclaimer in
        the documentation and/or other materials provided with the
        distribution.
     3. Neither the name of skimage nor the names of its contributors may be
        used to endorse or promote products derived from this software without
        specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
    IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
    DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
    INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
    SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
    HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
    STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
    IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
    POSSIBILITY OF SUCH DAMAGE.
    """
    if len(input_volume.shape) == 4:
        if vol_idx is not None:
            b0vol = np.mean(input_volume[..., tuple(vol_idx)], axis=3)
        else:
            b0vol = input_volume[..., 0].copy()
    else:
        b0vol = input_volume.copy()
    # Make a mask using a multiple pass median filter and histogram
    # thresholding.
    mask = multi_median(b0vol, median_radius, numpass)
    thresh = otsu(mask)
    mask = mask > thresh

    if dilate is not None:
        cross = generate_binary_structure(3, 1)
        mask = binary_dilation(mask, cross, iterations=dilate)

    # Auto crop the volumes using the mask as input_volume for bounding box
    # computing.
    if autocrop:
        mins, maxs = bounding_box(mask)
        mask = crop(mask, mins, maxs)
        croppedvolume = crop(input_volume, mins, maxs)
        maskedvolume = applymask(croppedvolume, mask)
    else:
        maskedvolume = applymask(input_volume, mask)
    return maskedvolume, mask
def imagen_auto_segmentada(prom_masDesvEstandar,
                           prom_menosDesvEstandar,
                           pintar=True):
    imagen_auto1 = np.zeros((220, 360), dtype="float64")
    imagen_auto2 = np.zeros((220, 360), dtype="float64")
    nombre = 0  #randint(1,339)
    detect = []
    for indice in range(100):
        nombre = indice + 1
        imagen = cv.imread("Autos/segmentacion/imagenes/%d.jpg" % nombre,
                           cv.IMREAD_GRAYSCALE)

        imagen_auto1 = imagen < prom_menosDesvEstandar
        imagen_auto2 = imagen > prom_masDesvEstandar
        imagen_or = np.bitwise_or(
            imagen_auto1, imagen_auto2)  #func_or(imagen_auto1,imagen_auto2)

        s = 10
        w = 5
        t = (((w - 1) / 2) - 0.5) / s
        imagen_filtrada = gaussian(imagen_or, sigma=s, truncate=t)

        imagen_filtrada = median(imagen_or, np.ones((10, 10)))
        umbral = otsu(imagen_filtrada)

        plt.title("Imagen_or_umbralada")
        plt.imshow(imagen_filtrada, cmap="gray")
        plt.savefig("Autos/segmentacion/programa/%d.jpg" % nombre)
        plt.show()
        imagen_filtrada = imagen_filtrada > umbral
        #print(imagen_filtrada.shape)
        region1 = imagen_filtrada[0:60, 0:360]
        region2 = imagen_filtrada[61:120, 0:360]
        region3 = imagen_filtrada[121:220, 0:360]
        pix_1 = np.sum(region1)
        pix_2 = np.sum(region2)
        pix_3 = np.sum(region3)
        #print(num_pixeles)
        num_1 = pix_1 / 1600
        num_2 = pix_2 / 3000
        num_3 = pix_3 / 5400
        num_autos = num_1 + num_2 + num_3
        redondeo = round(num_autos)
        detect.append(redondeo)
        print("pix_1 = {pixeles} Num autos = {autos}".format(pixeles=pix_1,
                                                             autos=num_1))
        print("pix_2 = {pixeles} Num autos = {autos}".format(pixeles=pix_2,
                                                             autos=num_2))
        print("pix_3 = {pixeles} Num autos = {autos}".format(pixeles=pix_3,
                                                             autos=num_3))
        print("Num_autos = {autos} redondeo = {red}".format(autos=num_autos,
                                                            red=redondeo))
        """
        umbral_rango = umbral * 255
        rango_imagen_filtrada = imagen_filtrada * 255
        rango_imagen_filtrada = np.array(rango_imagen_filtrada,dtype=np.uint8)
        
        histograma = np.zeros((256,1),dtype = np.double)
        filas,columnas = rango_imagen_filtrada.shape
        for i in range(filas):
            for j in range(columnas):
                histograma[rango_imagen_filtrada[i,j]][0] += 1
        
        linea = np.zeros((256,1),dtype = np.double)
        linea[int(umbral_rango)] = 600
        """
        if (pintar == True):
            plt.title('Imagen Auto leida %d' % nombre)
            plt.imshow(imagen, cmap='gray')
            plt.show()

            plt.title('Imagen Auto < prom_menosDesvEstandar')
            plt.imshow(imagen_auto1, cmap='gray')
            plt.savefig("imMenor_autos.jpg")
            plt.show()

            plt.title('Imagen Auto > prom_masDesvEstandar')
            plt.imshow(imagen_auto2, cmap='gray')
            plt.savefig("imMayor_autos.jpg")
            plt.show()

            plt.title("Imagen_or_umbralada")
            plt.imshow(imagen_filtrada, cmap="gray")
            plt.savefig("Autos/segmentacion/programa/%d.jpg" % nombre)
            plt.show()
            imagen_filtrada = imagen_filtrada > umbral
            num_pixeles = np.sum(imagen_filtrada)
            num_autos = num_pixeles / 4300
            redondeo = round(num_autos)
            print("Num pixeles = {pixeles} Num autos = {autos} redondeo={red}".
                  format(pixeles=num_pixeles, autos=num_autos, red=redondeo))

            plt.title("Imagen_or")
            plt.imshow(imagen_or, cmap="gray")
            plt.savefig("imOr_autos.jpg")
            plt.show()
            """
            plt.title('Histograma')
            plt.plot(histograma)
            plt.plot(linea)
            plt.text(int(umbral_rango),500,u'umbral_otsu',fontsize = 10,horizontalalignment = 'center')
            plt.axis([0,255,0,600])
            plt.show()
            """
    imagen_resultante = imagen * imagen_filtrada

    return imagen_resultante, detect
Example #9
0
    def extract_kidney_mask(self, outputPath=None):
        ''' Extract kidney mask in smallest resolution '''

        # Gaussian blur
        wsi_blur = gaussian(np.uint8(self.wsi), sigma=1)
        # gray level
        kidneyMask = rgb2gray(wsi_blur)
        # binary by OTSU thresholding
        thresh = otsu(kidneyMask, nbins=256)
        kidneyMask = kidneyMask <= thresh
        # morphological operations
        kidneyMask = binary_fill_holes(kidneyMask)
        kidneyMask = binary_opening(kidneyMask,
                                    structure=np.ones((3, 3)),
                                    iterations=3)

        # Get biggest area(s)
        labeledImg = label(kidneyMask)
        props = regionprops(labeledImg)

        all_areas = []
        for i, _ in enumerate(props):
            all_areas.append([props[i]['area'], i])
        all_areas.sort(reverse=True)

        # Deciding if there are one or two kidneys
        '''
        First extract the biggest area. 
        If:
            second biggest area is at least as big as half the first biggest area, 
                this WSI shows two kidneys.
            Extract mask for two kidneys.
        Else:
            Extract only one mask.
        '''
        kidney_areas = []
        ind = []

        if len(all_areas) == 1:
            kidney_areas.extend([all_areas[0][0]])
            ind.extend([all_areas[0][1]])
        elif all_areas[1][0] >= int(
                all_areas[0][0] * .5):  # bigger than 50% biggest area
            kidney_areas.extend([all_areas[0][0], all_areas[1][0]])
            ind.extend([all_areas[0][1], all_areas[1][1]])
        else:
            kidney_areas.extend([all_areas[0][0]])
            ind.extend([all_areas[0][1]])

        # Delete all small blobs from kidney mask
        for i, _ in enumerate(props):
            if i not in ind:
                coord = props[i]['bbox']
                kidneyMask[coord[0]:coord[2], coord[1]:coord[3]] = 0
        ''' If two kidneys, kidneyMask is a 3-channel image '''

        labeledImg = label(kidneyMask)
        props = regionprops(labeledImg)

        _, offset = self.get_params(self.slide.level_count - 1,
                                    self.highestOffset)

        self.all_coord = []
        if len(np.unique(labeledImg)) == 3:
            self.nr_kidneys = 2
            tempMask = np.zeros(
                (np.shape(labeledImg)[0], np.shape(labeledImg)[1], 3))
            for i, region in enumerate(props):
                coord = region['bbox']
                # To make sure all kidney tissue is covered while extracting patches
                coord = (max(coord[0] - offset, 0), max(coord[1] - offset, 0),
                         min(coord[2] + offset,
                             self.slide.level_dimensions[-1][1]),
                         min(coord[3] + offset,
                             self.slide.level_dimensions[-1][0]))
                self.all_coord.append(coord)
                tempMask[:, :,
                         i][coord[0]:coord[2],
                            coord[1]:coord[3]] = kidneyMask[coord[0]:coord[2],
                                                            coord[1]:coord[3]]

            kidneyMask = tempMask
        else:
            coord = props[0]['bbox']
            # To make sure all kidney tissue is covered while extracting patches
            coord = (max(coord[0] - offset, 0), max(coord[1] - offset, 0),
                     min(coord[2] + offset,
                         self.slide.level_dimensions[-1][1]),
                     min(coord[3] + offset,
                         self.slide.level_dimensions[-1][0]))
            self.all_coord = coord
            self.nr_kidneys = 1
        ''' Important for assigning kidneyIdentifier: 
            Upper/Left kidney = kidneyMask[:,:,0]
            Lower/Right kidney = kidneyMask[:,:,1] '''

        if self.nr_kidneys > 1:
            if self.all_coord[0][0] >= self.all_coord[1][0] or self.all_coord[
                    0][2] >= self.all_coord[1][2]:
                # swap coords
                self.all_coord[0], self.all_coord[1] = self.all_coord[
                    1], self.all_coord[0]
                # swap kidney images
                temp = np.zeros_like(kidneyMask[:, :, 0])
                temp = kidneyMask[:, :, 0].copy()
                kidneyMask[:, :, 0] = kidneyMask[:, :, 1]
                kidneyMask[:, :, 1] = temp

        # make sure user inputs valid kidneyIdentifier
        self.check_kidneyIdentifier(
            self.kidneyIdentifier
        )  # (self, kidneyIdentifier=self.kidneyIdentifier)
        # plt.imsave(os.path.join(outputPath, self.fileName + '_' + str(self.kidneyIdentifier) + '.jpg'), kidneyMask)

        return kidneyMask, self.all_coord, self.nr_kidneys
Example #10
0
def median_otsu(input_volume, vol_idx=None, median_radius=4, numpass=4,
                autocrop=False, dilate=None):
    """Simple brain extraction tool method for images from DWI data.

    It uses a median filter smoothing of the input_volumes `vol_idx` and an
    automatic histogram Otsu thresholding technique, hence the name
    *median_otsu*.

    This function is inspired from Mrtrix's bet which has default values
    ``median_radius=3``, ``numpass=2``. However, from tests on multiple 1.5T
    and 3T data     from GE, Philips, Siemens, the most robust choice is
    ``median_radius=4``, ``numpass=4``.

    Parameters
    ----------
    input_volume : ndarray
        3D or 4D array of the brain volume.
    vol_idx : None or array, optional.
        1D array representing indices of ``axis=3`` of a 4D `input_volume`.
        None is only an acceptable input if ``input_volume`` is 3D.
    median_radius : int
        Radius (in voxels) of the applied median filter (default: 4).
    numpass: int
        Number of pass of the median filter (default: 4).
    autocrop: bool, optional
        if True, the masked input_volume will also be cropped using the
        bounding box defined by the masked data. Should be on if DWI is
        upsampled to 1x1x1 resolution. (default: False).

    dilate : None or int, optional
        number of iterations for binary dilation

    Returns
    -------
    maskedvolume : ndarray
        Masked input_volume
    mask : 3D ndarray
        The binary brain mask

    Notes
    -----
    Copyright (C) 2011, the scikit-image team
    All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are
    met:

     1. Redistributions of source code must retain the above copyright
        notice, this list of conditions and the following disclaimer.
     2. Redistributions in binary form must reproduce the above copyright
        notice, this list of conditions and the following disclaimer in
        the documentation and/or other materials provided with the
        distribution.
     3. Neither the name of skimage nor the names of its contributors may be
        used to endorse or promote products derived from this software without
        specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
    IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
    DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
    INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
    SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
    HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
    STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
    IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
    POSSIBILITY OF SUCH DAMAGE.
    """
    if len(input_volume.shape) == 4:
        if vol_idx is not None:
            b0vol = np.mean(input_volume[..., tuple(vol_idx)], axis=3)
        else:
            raise ValueError("For 4D images, must provide vol_idx input")
    else:
        b0vol = input_volume
    # Make a mask using a multiple pass median filter and histogram
    # thresholding.
    mask = multi_median(b0vol, median_radius, numpass)
    thresh = otsu(mask)
    mask = mask > thresh

    if dilate is not None:
        cross = generate_binary_structure(3, 1)
        mask = binary_dilation(mask, cross, iterations=dilate)

    # Auto crop the volumes using the mask as input_volume for bounding box
    # computing.
    if autocrop:
        mins, maxs = bounding_box(mask)
        mask = crop(mask, mins, maxs)
        croppedvolume = crop(input_volume, mins, maxs)
        maskedvolume = applymask(croppedvolume, mask)
    else:
        maskedvolume = applymask(input_volume, mask)
    return maskedvolume, mask
Example #11
0
def compute_hardi_bounds(data, alpha, mask=None):
    """ Compute fidelity bounds for (subdomain) of HARDI signal `data`.

    Args:
        data : QBallData, data description
            data.raw : numpy array of shape (B,X,Y,Z,L)
                three-dim. (B-batch of) HARDI signals with L b-vectors
            data.slice : indexing into (X,Y,Z) of raw data
                bounds are only computed for this slice
            data.b_sph : Sphere object from b-vectors
        alpha : confidence level
        mask : numpy array of shape (X,Y,Z)
            foreground mask, containing only 1s and 0s

    Returns:
        nothing, sets data.bounds to (alpha, fl, fu), where
        fl, fu : numpy arrays of shape (L,N)
            lower and upper bounds for averaged log(-log(data))
            the image dimensions are raveled
    """
    if data.bounds is not None and data.bounds_alpha == alpha:
        return

    data_raw = np.array(data.raw, dtype=np.float64)
    if len(data_raw.shape) < 5:
        data_raw = data_raw[None]
    where_b0 = (data.gtab.bvals == 0)
    where_dwi = (data.gtab.bvals > 0)

    # scale data to [0.0,0.8] (restored after parameter estimation)
    scaling_factor = np.amax(data_raw.ravel()) / 0.8
    data_raw /= scaling_factor

    b_batch = data_raw.shape[0]
    l_labels = data.b_sph.mdims['l_labels']

    if mask is None:
        # automatically estimate foreground from histogram thresholding (Otsu)
        mask = np.mean(data_raw[..., where_dwi], axis=(0, -1))
        thresh = otsu(mask)
        mask = (mask <= thresh)
        if len(mask[data.slice].shape) == 2:
            logging.debug("\n%s" % matrix2brl(mask[data.slice].astype(int)))
    mask = np.tile(mask, (1, 1, 1, data_raw.shape[-1])).ravel()
    sigma = rice_sigma_mle(data_raw.reshape(b_batch, -1), mask)
    logging.info('Rescaled sigma=%.5f.', sigma * scaling_factor)

    logging.info(
        'Computing confidence intervals with confidence level %.3f'
        ' from batch of size %d...', alpha, b_batch)
    data_sliced = data_raw[(slice(None), ) + data.slice]
    imagedims = data_sliced.shape[1:-1]
    n_image = np.prod(imagedims)
    data_flat = data_sliced.reshape(b_batch, -1)
    _, data_l, data_u = rice_nu_paramci_batch(data_flat, sigma, alpha)

    # -------------- Postprocessing of bounds ----------------------------------

    # Restore original scaling
    data_l = scaling_factor * data_l.reshape(data_sliced.shape)
    data_u = scaling_factor * data_u.reshape(data_sliced.shape)

    # normalize data according to b0-image
    if not data.normed:
        data_l.clip(1.0, out=data_l)
        data_u.clip(1.0, out=data_u)
        b0_l = data_l[..., where_b0].mean(-1)
        b0_u = data_u[..., where_b0].mean(-1)
        data_l /= b0_u[..., None]
        data_u /= b0_l[..., None]
    data_l = data_l[..., where_dwi]
    data_u = data_u[..., where_dwi]

    # clip data away from 0 and 1
    clip_hardi_data(data_l)
    clip_hardi_data(data_u)
    assert ((data_l <= data_u).all())

    # apply log(-log)
    fl = np.zeros((l_labels, n_image), order='C')
    fu = np.zeros((l_labels, n_image), order='C')
    fl[:] = np.log(-np.log(data_u)).reshape(-1, l_labels).T
    fu[:] = np.log(-np.log(data_l)).reshape(-1, l_labels).T
    assert ((fl <= fu).all())

    # subtract mean
    fl_mean = np.einsum('ki,k->i', fl, data.b_sph.b) / (4 * np.pi)
    fu_mean = np.einsum('ki,k->i', fu, data.b_sph.b) / (4 * np.pi)
    fu -= fl_mean
    fl -= fu_mean

    data.bounds = (alpha, fl, fu)
Example #12
0
def imagen_auto_segmentada(prom_masDesvEstandar,prom_menosDesvEstandar,pintar=True):
    imagen_auto1 = np.zeros((230,350),dtype="float64")
    imagen_auto2 = np.zeros((230,350),dtype="float64")
    nombre = 0#randint(1,339)
    detect = []
    for indice in range(100):
        nombre = indice + 1 
        imagen = cv.imread("Personas/segmentacion/imagenes/%d.jpg"%nombre,cv.IMREAD_GRAYSCALE)    
        
        imagen_auto1 = imagen < prom_menosDesvEstandar    
        imagen_auto2 = imagen > prom_masDesvEstandar   
        imagen_or = np.bitwise_or(imagen_auto1,imagen_auto2)   #func_or(imagen_auto1,imagen_auto2)
        
        s = 10
        w = 3
        t = (((w-1)/2)-0.5)/s
        imagen_filtrada = gaussian(imagen_or,sigma = s,truncate = t)
        imagen_filtrada = median(imagen_or,np.ones((5,5)))
        umbral = otsu(imagen_filtrada)
        imagen_filtrada = imagen_filtrada > umbral
        
        imagen_resultante = imagen * imagen_filtrada
        num_pixeles = np.sum(imagen_filtrada)
        num_personas = num_pixeles / 1200
        num_personas_t = round(num_personas)
        detect.append(num_personas_t)
        plt.title('Imagen filtrada')
        plt.imshow(imagen_filtrada,cmap='gray')
        plt.savefig("Personas/segmentacion/programa/%d.jpg"%nombre)
        plt.show()
        print("{cont} Num pixeles = {pixeles} Num personas = {personas} round={trun}".format(cont=nombre,pixeles = num_pixeles,personas=num_personas,trun=num_personas_t))
        """
        umbral_rango = umbral * 255
        
        rango_imagen_filtrada = imagen_filtrada * 255
        rango_imagen_filtrada = np.array(rango_imagen_filtrada,dtype=np.uint8)
        
        histograma = np.zeros((256,1),dtype = np.double)
        filas,columnas = rango_imagen_filtrada.shape
        for i in range(filas):
            for j in range(columnas):
                histograma[rango_imagen_filtrada[i,j]][0] += 1
                
        linea = np.zeros((256,1),dtype = np.double)
        linea[int(umbral_rango)] = 600
        """
        if(pintar == True):
            plt.title('Imagen leida %d'%nombre)
            plt.imshow(imagen,cmap='gray')
            plt.show()
            
            plt.title('Imagen filtrada')
            plt.imshow(imagen_filtrada,cmap='gray')
            plt.savefig("Personas/segmentacion/programa/%d.jpg"%nombre)
            plt.show()
            
            plt.title("Imagen segmentada")
            plt.imshow(imagen_resultante,cmap="gray")
            plt.savefig("imSegmentada_personas.jpg")
            plt.show()
            
            plt.title('Imagen leida < prom_menosDesvEstandar')
            plt.imshow(imagen_auto1,cmap='gray')
            plt.savefig("imMenor_personas.jpg")
            plt.show()
                
            plt.title('Imagen Auto > prom_masDesvEstandar')
            plt.imshow(imagen_auto2,cmap='gray')
            plt.savefig("imMayor_personas.jpg")
            plt.show()
            """
            plt.title("Imagen_or")
            plt.imshow(imagen_or,cmap="gray")
            plt.savefig("imSegmentada_personas.jpg")
            #plt.savefig("Personas/resultadoPersonas/%d.jpg"%nombre)
            plt.show() 
            
           
            
            plt.title('Histograma')
            plt.plot(histograma)
            plt.plot(linea)
            plt.text(int(umbral_rango),500,u'umbral_otsu',fontsize = 10,horizontalalignment = 'center')
            plt.axis([0,255,0,600])
            plt.show()
            """
    
    
    return imagen_resultante,detect
Example #13
0
def median_otsu(input_volume, median_radius=4, numpass=4,
                autocrop=False, vol_idx=None, dilate=None):
    """ Simple brain extraction tool method for images from DWI data

    It uses a median filter smoothing of the input_volumes `vol_idx` and an
    automatic histogram Otsu thresholding technique, hence the name
    *median_otsu*.

    This function is inspired from Mrtrix's bet which has default values
    ``median_radius=3``, ``numpass=2``. However, from tests on multiple 1.5T
    and 3T data     from GE, Philips, Siemens, the most robust choice is
    ``median_radius=4``, ``numpass=4``.

    Parameters
    ----------
    input_volume : ndarray
        ndarray of the brain volume
    median_radius : int
        Radius (in voxels) of the applied median filter(default 4)
    numpass: int
        Number of pass of the median filter (default 4)
    autocrop: bool, optional
        if True, the masked input_volume will also be cropped using the bounding
        box defined by the masked data. Should be on if DWI is upsampled to 1x1x1
        resolution. (default False)
    vol_idx : None or array, optional
        1D array representing indices of ``axis=3`` of a 4D `input_volume`
        None (the default) corresponds to ``(0,)`` (assumes first volume in 4D array)
    dilate : None or int, optional
        number of iterations for binary dilation

    Returns
    -------
    maskedvolume : ndarray
        Masked input_volume
    mask : 3D ndarray
        The binary brain mask
    """
    if len(input_volume.shape) == 4:
        if vol_idx is not None:
            b0vol = np.mean(input_volume[..., tuple(vol_idx)], axis=3)
        else:
            b0vol = input_volume[..., 0].copy()
    else:
        b0vol = input_volume.copy()
    # Make a mask using a multiple pass median filter and histogram thresholding.
    mask = multi_median(b0vol, median_radius, numpass)
    thresh = otsu(mask)
    mask = mask > thresh

    if dilate is not None:
        cross = generate_binary_structure(3, 1)
        mask = binary_dilation(mask, cross, iterations=dilate)

    # Auto crop the volumes using the mask as input_volume for bounding box computing.
    if autocrop:
        mins, maxs = bounding_box(mask)
        mask = crop(mask, mins, maxs)
        croppedvolume = crop(input_volume, mins, maxs)
        maskedvolume = applymask(croppedvolume, mask)
    else:
        maskedvolume = applymask(input_volume, mask)
    return maskedvolume, mask
Example #14
0
        return 'tangerine'
    else:
        return 'unknown'


f = open('feature.csv', 'w')
f.write(
    'area,bbox_area,centroidX,centroidY,convex_area,eccentricity,equivalent_diameter,euler_number,extent,filled_area,major_axis_length,.minor_axis_length,orientation,perimeter,solidity,kelas\n'
)
for i in os.listdir('.'):
    if i.endswith('.jpg'):
        temp = i.split('.')
        kelas = leavesClass(int(temp[0]))
        img = io.imread(i)
        imgGray = rgb2gray(img)
        threshold = otsu(imgGray, 256)
        x, y = imgGray.shape
        for k in range(x):
            for l in range(y):
                if imgGray[k][l] > threshold:
                    imgGray[k][l] = 0
                else:
                    imgGray[k][l] = 1

        imgLabel = label(imgGray)
        props = regionprops(imgLabel)
        centroid = props[0].centroid
        f.write(
            str(props[0].area) + ',' + str(props[0].bbox_area) + ',' +
            str(centroid[0]) + ',' + str(centroid[1]) + ',' +
            str(props[0].convex_area) + ',' + str(props[0].eccentricity) +