コード例 #1
0
    def extract_image_features(self, data):
        # Please do not modify the header above

        # extract feature vector from image data

        feature_data = []

        for i in data:
            # 1. PREPROCESSING: grayscaling
            i = color.rgb2gray(i)
            # 1. PREPROCESSING: gaussian blur
            i = filters.gaussian(i, sigma=(0.6, 0.6))
            # 1. PREPROCESSING: thresholding to get black and white (as displayed in pdf)
            thresh = filters.threshold_minimum(i)
            binary_image = i > thresh

            # Couldn't resolve error related to putting a boolean image array inside hog, had to use image without thresholding
            # 2. FEATURE DESCRIPTOR: HOG
            (feature_i, hog_image) = feature.hog(i,
                                                 orientations=8,
                                                 pixels_per_cell=(32, 32),
                                                 cells_per_block=(2, 2),
                                                 visualize=True,
                                                 multichannel=False)

            feature_data.append(feature_i)
            # FOR TESTING PURPOSES ONLY
            # print(H.size)
            # io.imshow(hog_image)
            # plt.show()

        feature_data = np.array(feature_data)
        # Please do not modify the return type below
        return feature_data
コード例 #2
0
def initial_segmentation(image, PATCH_RATIO):
    """
    Initialization of the image segmentation.
 
    :param image: A numpy matrix. Original image.
    :param PATCH_RATIO: Constant. Ratio between patch area against cell mean cell area.
    """
    from skimage.filters import threshold_li, threshold_otsu, threshold_minimum
    from skimage.morphology import closing, square
    thresh_li = threshold_li(image)
    thresh_otsu = threshold_otsu(image)
    try:
        thresh_min = threshold_minimum(image)
    except RuntimeError:
        thresh_min = thresh_otsu + 100

    if thresh_min < thresh_otsu:
        threshold_steps = range(int(thresh_li), int(thresh_otsu),
                                abs(int((thresh_otsu - thresh_li) / 5)))
    else:
        threshold_steps = [thresh_otsu]
    binary_image = closing(image > threshold_steps[0], square(3))
    label_image = label(binary_image)
    regions = regionprops(label_image, image)
    regions_above_noise = []
    areas = []
    for region in regions:
        if region.area >= 9:
            #Lista con las nuevas regiones
            areas.append(region.area)
            regions_above_noise.append(region)

    median = np.median(areas)
    patch = int((PATCH_RATIO * median)**(0.5))
    return (threshold_steps, patch, regions_above_noise, label_image)
コード例 #3
0
    def call_doublets(self, threshold=None, verbose=True):
        if threshold is None:
            # automatic threshold detection
            # http://scikit-image.org/docs/dev/api/skimage.filters.html
            from skimage.filters import threshold_minimum
            try:
                threshold = threshold_minimum(self.doublet_scores_sim_)
                if verbose:
                    print("Automatically set threshold at doublet score = {:.2f}".format(threshold))
            except:
                self.predicted_doublets_ = None
                if verbose:
                    print("Warning: failed to automatically identify doublet score threshold. Run `call_doublets` with user-specified threshold.")
                return self.predicted_doublets_

        Ld_obs = self.doublet_scores_obs_
        Ld_sim = self.doublet_scores_sim_
        se_obs = self.doublet_errors_obs_
        Z = (Ld_obs - threshold) / se_obs
        self.predicted_doublets_ = Ld_obs > threshold
        self.z_scores_ = Z
        self.threshold_ = threshold
        self.detected_doublet_rate_ = (Ld_obs>threshold).sum() / float(len(Ld_obs))
        self.detectable_doublet_fraction_ = (Ld_sim>threshold).sum() / float(len(Ld_sim))
        self.overall_doublet_rate_ = self.detected_doublet_rate_ / self.detectable_doublet_fraction_

        if verbose:
            print('Detected doublet rate = {:.1f}%'.format(100*self.detected_doublet_rate_))
            print('Estimated detectable doublet fraction = {:.1f}%'.format(100*self.detectable_doublet_fraction_))
            print('Overall doublet rate:')
            print('\tExpected   = {:.1f}%'.format(100*self.expected_doublet_rate))
            print('\tEstimated  = {:.1f}%'.format(100*self.overall_doublet_rate_))
            
        return self.predicted_doublets_
コード例 #4
0
def analyze_minThreshold(image):
    """Returns bright on dark particles using a thresholding algorithm

    Implements contrast stretching and minimum thresholding to detect particles
    Cleanup is performed by closing and removing the particles that contact the clear_border
    """
    #Convert to grayscale
    i_grey = rgb2gray(image)
    #Convert to uint8
    i_uint = img_as_ubyte(i_grey)
    #Contrast stretching
    p2, p98 = np.percentile(i_uint, (2, 98))
    i_contStretch = exposure.rescale_intensity(i_uint, in_range=(p2, p98))
    #Minimum thresholding
    i_min_thresh = i_uint > threshold_minimum(i_contStretch)
    #Close open domains
    i_closed = closing(i_min_thresh, square(3))
    #Remove artifacts connected to image border
    i_cleared = clear_border(i_closed)
    #Label image regions
    label_image = label(i_cleared)
    #Extract region properties
    partProps = regionprops(label_image, intensity_image=i_grey)

    #Return
    return partProps
コード例 #5
0
    def handleBFOTO(self):
        #view = 0
        v = 0
        self.views[v].clear()
        
        #TODO take picture with webcam (openCV)
        os.system("streamer -c /dev/video1 -s 1280x960 -o ./img/foto.ppm")
        #os.system("streamer -c /dev/video0 -s 1920x1080 -o ./img/foto.ppm")
        os.system("convert ./img/foto.ppm ./img/test.png")
        
        
        path = './img/test.png' 

        img = rgb2gray(io.imread(path))
        #img = equalize_hist(rgb2gray(io.imread(path)))
        io.imsave('./img/testGRAY.png', img)
        
        
        # thresholding
        #thresh = threshold_mean(img)
        #thresh = threshold_otsu(img)
        thresh = threshold_minimum(img)
        print(thresh)
        binary = img > thresh
        io.imsave('./img/testTH.png', img_as_uint(binary))
        
        # adaptive thresholding
        #block_size = 35
        #adaptive_thresh = threshold_local(img, block_size, offset=10)
        #binary_adaptive = img > adaptive_thresh        
        #io.imsave('./testTHadapt.png', img_as_uint(binary))

        # load iamge
        path = './img/testTH.png' 
        self.loadIMG(path,v)
コード例 #6
0
ファイル: _io.py プロジェクト: ElaneKou/pendantdrop
def _auto_crop(image, expand=20):
    """
    Automated-crop based on the biggest darkest object.


    Parameters
    ----------
    image : ndarray
        Full image.
    expand : scalar
        Expand by this number of pixels.

    Returns
    -------
    cropped


    Notes
    -----
    The original image is thresholded with a minimum threshold to get the
    darkest pixels.
    """
    import numpy as np
    from skimage import measure
    from skimage import filters
    darkest = image < filters.threshold_minimum(image)
    labels = measure.label(darkest)
    props = measure.regionprops(labels)
    areas = np.array([prop.area for prop in props])
    bb = props[areas.argmax()].bbox
    return image[bb[0] - expand:bb[2] + expand, bb[1] - expand:bb[3] + expand]
コード例 #7
0
def preprocess(filename):
    """Perform image processing to isolate characters from page background"""
    # Read in image
    filename_wo_extension = filename.split('.')[0]
    page = io.imread(filename, as_grey=True)

    # Blur the image
    page_blur = filters.gaussian(page)

    # Logarithmic correction to even background color
    page_logarithmic_corrected = exposure.adjust_log(page_blur, 1)

    # Increase contrast
    p3, p98 = np.percentile(page_logarithmic_corrected, (3, 98))
    page_contrast = exposure.rescale_intensity(page_logarithmic_corrected, in_range=(p3, p98))

    # Separate characters from background and remove anythind touching the edge
    page_filter = page_contrast < filters.threshold_minimum(page_contrast)
    page_filter = segmentation.clear_border(page_filter)

    # Remove specks
    page_clean = morphology.remove_small_objects(page_filter, 30)

    # Dilate characters
    page_dilate = morphology.binary_dilation(page_clean);
    page_dilate = morphology.binary_dilation(page_dilate);
    page_dilate = morphology.binary_dilation(page_dilate);
    page_dilate = morphology.binary_dilation(page_dilate);

    return page_dilate
def crop_im(pil_image):
    w, h = pil_image.size
    if w > 1000:
        pil_image = tr.Resize([1000, 1000])(pil_image)
    try:
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            with np.errstate(divide='ignore'):
                im = np.array(pil_image)
                im_v = equalize_adapthist(rgb2hsv(im)[:, :, 2])
                thresh = threshold_minimum(im_v)
                binary = im_v > thresh
                label_img = label(binary)
                regions = regionprops(label_img)
                areas = [r.area for r in regions]
                largest_cc_idx = np.argmax(areas)
                fov = regions[largest_cc_idx]
                cropped = im[fov.bbox[0]:fov.bbox[2],
                             fov.bbox[1]:fov.bbox[3], :]
                fov_im = binary_fill_holes(regions[largest_cc_idx].image)

                if cropped.shape[1] > 512:
                    return Image.fromarray(cropped), Image.fromarray(
                        255 * fov_im.astype('uint8'))
                else:
                    return pil_image, Image.fromarray(
                        255 * np.ones(pil_image.size).astype('uint8'))
    except:
        return pil_image, Image.fromarray(
            255 * np.ones(pil_image.size).astype('uint8'))
コード例 #9
0
    def __call__(self, img):
        # img is a numpy rgb image
        grey_img = rgb2grey(img)
        t1 = filters.threshold_minimum(grey_img)
        t2 = filters.threshold_yen(grey_img)

        img1 = mark_boundaries(img, (grey_img > t1), color=(1, 0, 0))
        img1 = mark_boundaries(img1, (grey_img > t2), color=(1, 0, 0))
        img2 = mark_boundaries(img, grey_img < 0)
        img = ((img1 + img2) / 2)

        #img = mark_boundaries(img, quickshift(img_as_float(img), kernel_size =5, max_dist = 10, ratio = 1.0))

        #img = mark_boundaries(img, slic(img_as_float(img), n_segments=10))
        #fimg = rgb2grey(img)
        #t = filters.threshold_otsu(fimg)
        #img = mark_boundaries(img, (fimg > t).astype(np.uint8), color=(1,0,0))
        #img  = mark_boundaries(img, (fimg - filters.threshold_niblack(fimg)< 0).astype(np.uint8), color=(1,0,0))

        #img_gray = rgb2grey(img)
        #img_gray = img[:, :, 1]
        # morphological opening (size tuned on training data)
        #circle7 = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (7, 7))
        #img_open = cv2.morphologyEx(img_gray, cv2.MORPH_OPEN, circle7)
        # Otsu thresholding
        #img_th = cv2.threshold(img_open, 0, 255, cv2.THRESH_OTSU)[1]
        # Invert the image in case the objects of interest are in the dark side
        #if (np.sum(img_th == 255) > np.sum(img_th == 0)):
        #    img_th = cv2.bitwise_not(img_th)
        # second morphological opening (on binary image this time)
        #bin_open = cv2.morphologyEx(img_th, cv2.MORPH_OPEN, circle7)
        # connected components
        #img = mark_boundaries(img,cv2.connectedComponents(bin_open)[1], color=(1,0,0))

        return (img * 255).astype(np.uint8)
コード例 #10
0
ファイル: utils.py プロジェクト: apuayush/DNA_SRA
def threshold(image):
    """ Does thresholding
    """
    image = np.asarray(image)
    image = np.dot(image[...,:3], [0.299, 0.587, 0.114])
    thresh = threshold_minimum(image[:,:])
    return image[:,:] > thresh
コード例 #11
0
def binary(img, method):
    """Threshold image

    :param img: grayscale image (numpy array)
    :param method: thresholding method
    :return: binary image
    """
    if method == 'otsu':
        thresh = threshold_otsu(img)
        binary = img > thresh

    elif method == 'mean':
        thresh = threshold_mean(img)
        binary = img > thresh
        binary = 1 - binary

    elif method == 'local':
        thresh = threshold_local(img, 35, offset=10)
        binary = img > thresh

    else:
        thresh = threshold_minimum(img)
        binary = img > thresh

    return binary
コード例 #12
0
def analyze_watershed(image):
    """Returns bright on dark particles using a watershed algorithm

    Implements contrast stretching, sobel edge detection and a watershed algortihm to detect particles
    Cleanup is performed by closing and removing the particles that contact the clear_border
    """
    #Convert to grayscale
    i_grey = rgb2gray(image)
    #Convert to uint8
    i_uint = img_as_ubyte(i_grey)
    #Contrast stretching
    p2, p98 = np.percentile(i_uint, (2, 98))
    i_contStretch = exposure.rescale_intensity(i_uint, in_range=(p2, p98))
    #Construct elevation map
    elevation_map = sobel(i_contStretch)
    #Create markers using extremes of the intensity histogram
    markers = np.zeros_like(i_uint)
    threshold = threshold_minimum(i_contStretch)
    markers[i_uint < 0.7 * threshold] = 1
    markers[i_uint > 1.3 * threshold] = 2
    #Apply the watershed algorithm for segmentation
    i_segmented = watershed(elevation_map, markers)
    #Close open domains
    i_closed = closing(i_segmented, square(3))
    #Remove artifacts connected to image border
    i_cleared = clear_border(i_closed)
    #Label image regions
    label_image = label(i_cleared)
    #Extract region properties
    partProps = regionprops(label_image, intensity_image=i_grey)

    #Return
    return partProps
コード例 #13
0
    def call_doublets(self, threshold=None, verbose=True):
        ''' Call trancriptomes as doublets or singlets

        Arguments
        ---------
        threshold : float, optional (default: None) 
            Doublet score threshold for calling a transcriptome
            a doublet. If `None`, this is set automatically by looking
            for the minimum between the two modes of the `doublet_scores_sim_`
            histogram. It is best practice to check the threshold visually
            using the `doublet_scores_sim_` histogram and/or based on 
            co-localization of predicted doublets in a 2-D embedding.

        verbose : bool, optional (default: True)
            If True, print summary statistics.

        Sets
        ----
        predicted_doublets_, z_scores_, threshold_,
        detected_doublet_rate_, detectable_doublet_fraction, 
        overall_doublet_rate_
        '''

        if threshold is None:
            # automatic threshold detection
            # http://scikit-image.org/docs/dev/api/skimage.filters.html
            from skimage.filters import threshold_minimum
            threshold = threshold_minimum(self.doublet_scores_sim_)

            if verbose:
                print("Automatically set threshold at doublet score = {:.2f}".
                      format(threshold))

        Ld_obs = self.doublet_scores_obs_
        Ld_sim = self.doublet_scores_sim_
        se_obs = self.doublet_errors_obs_
        Z = (Ld_obs - threshold) / se_obs
        self.predicted_doublets_ = Ld_obs > threshold
        self.z_scores_ = Z
        self.threshold_ = threshold
        self.detected_doublet_rate_ = (Ld_obs > threshold).sum() / float(
            len(Ld_obs))
        self.detectable_doublet_fraction_ = (Ld_sim > threshold).sum() / float(
            len(Ld_sim))
        self.overall_doublet_rate_ = self.detected_doublet_rate_ / self.detectable_doublet_fraction_

        if verbose:
            print('Detected doublet rate = {:.1f}%'.format(
                100 * self.detected_doublet_rate_))
            print('Estimated detectable doublet fraction = {:.1f}%'.format(
                100 * self.detectable_doublet_fraction_))
            print('Overall doublet rate:')
            print('\tExpected   = {:.1f}%'.format(100 *
                                                  self.expected_doublet_rate))
            print('\tEstimated  = {:.1f}%'.format(100 *
                                                  self.overall_doublet_rate_))

        return self.predicted_doublets_
コード例 #14
0
def thinning(image_abs_path,i):
	grayscale_img = imread(image_abs_path, as_gray=True)
	gaussian_blur = gaussian(grayscale_img, sigma=1)
	thresh_sauvola = threshold_minimum(gaussian_blur)
	binary_img = gaussian_blur < thresh_sauvola
	thinned_img = skeletonize(binary_img)
	thinned_img = thinned_img == 0
	plt.imsave('output.png',thinned_img, format="png", cmap="hot") 
	plt.imsave('output_'+str(i)+'.png',thinned_img, format="png", cmap="hot")
コード例 #15
0
ファイル: images.py プロジェクト: jgranley/pulse2percept
    def threshold(self, thresh, **kwargs):
        """Threshold the image

        Parameters
        ----------
        thresh : str or float
            If a float in [0,1] is provided, pixels whose grayscale value is
            above said threshold will be white, others black.

            A number of additional methods are supported:

            *  'mean': Threshold image based on the mean of grayscale values.
            *  'minimum': Threshold image based on the minimum method, where
                          the histogram of the input image is computed and
                          smoothed until there are only two maxima.
            *  'local': Threshold image based on `local pixel neighborhood
                        <https://scikit-image.org/docs/stable/api/skimage.filters.html#skimage.filters.threshold_local>_.
                        Requires ``block_size``: odd number of pixels in the
                        neighborhood.
            *  'otsu': `Otsu's method
                       <https://scikit-image.org/docs/stable/api/skimage.filters.html#skimage.filters.threshold_otsu>_
            *  'isodata': `ISODATA method
                          <https://scikit-image.org/docs/stable/api/skimage.filters.html#skimage.filters.threshold_isodata>`_,
                          also known as the Ridler-Calvard method or
                          intermeans.

        Returns
        -------
        stim : `ImageStimulus`
            A copy of the stimulus object with two gray levels 0.0 and 1.0
        """
        if len(self.img_shape) > 2:
            raise ValueError("Thresholding is only supported for grayscale "
                             "(i.e., single-channel) images. Use `rgb2gray` "
                             "first.")
        img = self.data.reshape(self.img_shape)
        if isinstance(thresh, str):
            if thresh.lower() == 'mean':
                img = img > threshold_mean(img)
            elif thresh.lower() == 'minimum':
                img = img > threshold_minimum(img, **kwargs)
            elif thresh.lower() == 'local':
                img = img > threshold_local(img, **kwargs)
            elif thresh.lower() == 'otsu':
                img = img > threshold_otsu(img, **kwargs)
            elif thresh.lower() == 'isodata':
                img = img > threshold_isodata(img, **kwargs)
            else:
                raise ValueError("Unknown threshold method '%s'." % thresh)
        elif np.isscalar(thresh):
            img = self.data.reshape(self.img_shape) > thresh
        else:
            raise TypeError("Threshold type must be str or float, not "
                            "%s." % type(thresh))
        return ImageStimulus(img,
                             electrodes=self.electrodes,
                             metadata=self.metadata)
コード例 #16
0
ファイル: draw_pixels.py プロジェクト: PuchnerLab/dmd-control
 def load_image(self, filename):
     new_image = io.imread(filename, as_gray=True)
     new_image = (np.iinfo(self.camera.dtype).max *
                  (new_image / new_image.max()))
     new_image = transform.resize(new_image, self.camera.shape).astype(
         self.camera.dtype)
     new_image = new_image > filters.threshold_minimum(new_image)
     self.camera[:] = np.iinfo(self.camera.dtype).max * new_image.astype(
         self.camera.dtype).copy()
コード例 #17
0
ファイル: water_functions.py プロジェクト: jziemer1996/Wateks
def threshold_minimum(arr1d):
    """
    doesnt work: Unable to find two maxima in histogram
    :param arr1d:
    :return:
    """
    import skimage.filters as sf
    thresh = sf.threshold_minimum(arr1d, nbins=256, max_iter=100)
    return thresh
コード例 #18
0
class BinaryAlg:
    _operations = {     
    'Isodata': lambda x : 1*((abs(x) > skfilters.threshold_isodata(x))),    
    'Li': lambda x : 1*((abs(x) > skfilters.threshold_li(x))), 
    'Mean': lambda x : 1*((abs(x) > skfilters.threshold_mean(x))),
    'Minimum': lambda x : 1*((abs(x) > skfilters.threshold_minimum(x))),
    'Otsu': lambda x : 1*((abs(x) > skfilters.threshold_otsu(x))),
    'Triangle': lambda x : 1*((abs(x) > skfilters.threshold_triangle(x))),
    'Yen': lambda x : 1*((abs(x) > skfilters.threshold_yen(x)))
    }   
コード例 #19
0
def create_stare_mask(image, image_path=None):
    im_gray = rgb2gray(image)
    thresh_val = threshold_minimum(im_gray)
    mask = np.where(im_gray > thresh_val, 1, 0)
    # Make sure the larger portion of the mask is considered background
    if np.sum(mask == 0) < np.sum(mask == 1):
        mask = np.where(mask, 0, 1)
    if image_path:
        save_image(image_path, mask)
    return mask
コード例 #20
0
def region_analyzer(I, pts, maxitter=100):
    Igg = I.copy()  #going to make BW img out of green channel
    Igg[:, :, 0] = Igg[:, :, 1]  #red and blue get same values as green channel
    Igg[:, :, 2] = Igg[:, :, 1]
    thresh = threshold_minimum(Igg)
    #cutoff between B & W ####MAY NEED TO CHANGE IF IT DOESNT WORK
    detect = 0
    itter = 0
    while pts > detect:

        IBinary = (Igg[:, :, 2] > thresh
                   )  #array where true at brightness > threshold
        #        plt.imshow(IBinary)

        IBinaryFix = clear_border(1 - closing(IBinary, square(3)))
        #        plt.imshow(IBinaryFix)
        label_image = label(
            IBinaryFix)  # find and lable all white contiguous shapes
        region_properties = regionprops(
            label_image)  #get properties of labeled regions
        #    #For all the properties you can assess see:
        #    #         http://scikit-image.org/docs/dev/api/skimage.measure.html
        n = len(region_properties)  #number of objects detected
        e = np.zeros(n)  #container for our eccentricities
        middle = np.zeros([n, 2])
        i = 0
        dim = np.shape(I)
        tol = 0.001 * (
            dim[0] * dim[1]
        )  #####May need to change if it doesnt work based on picture and dot size
        param_save = np.zeros([n, 4])
        for region in region_properties:
            # take regions with large enough areas
            if region.filled_area >= tol:
                # draw rectangle around segmented coins
                minr, minc, maxr, maxc = region.bbox  #object's bounding box
                param_save[i, :] = np.array([minr, minc, maxr, maxc])
                e[i] = region.eccentricity  #closer to 0 is closer to circle
                #                    bx = (minc, maxc, maxc, minc, minc)
                #                    by = (minr, minr, maxr, maxr, minr)
                y0, x0 = region.centroid

                #                plt.plot(bx, by, '-b', linewidth=2.5)
                #                plt.plot(x0,y0,'or')
                middle[i, :] = x0, y0
                i += 1  #advance
        detect = len(np.nonzero(e)[0])
        if np.mean(IBinary) > 0.5:
            thresh = thresh + 0.01 * thresh
        elif np.mean(IBinary <= 0.5):
            thresh = thresh - 0.01 * thresh
        itter += 1
        if itter == maxitter:
            break
        return e, middle
コード例 #21
0
 def thresh(self):
     """Automatically choose a threshold based on the counts"""
     try: 
         thresh = threshold_minimum(np.array(self.c), 25)
         int(np.log(thresh)) # ValueError if thresh <= 0 
         self.t = int(thresh)
     except (ValueError, RuntimeError, OverflowError): 
         try:
             self.t = int(0.5*(max(self.c) + min(self.c)))
             int(np.log(self.t)) # ValueError if thresh <= 0 
         except (ValueError, TypeError, OverflowError):
             self.t = 1
     self.threshedit.setText(str(self.t))
コード例 #22
0
def rgb2gray(filepath):
    '''
    Function
    - takes filepath of image,
    - converts image to gray scale,
    - resizes, downsamples and denoises image (optional)
    - flattens image to vector of length 424*424

    returns vector
    '''
    img = imread(filepath)
    if (gray):
        gray_img = np.dot(img[..., :3], [0.299, 0.587, 0.144])
    else:
        gray_img = np.asarray(img)
        gray_img = gray_img.astype('float32')

    if (scaling == True):
        start = 424 // 2 - scaling_param // 2
        stop = 424 // 2 + scaling_param // 2
        gray_img = gray_img[start:stop, start:stop]
    if (downsampling == True):
        gray_img = downscale_local_mean(gray_img, (ds_param, ds_param))
    if (normalising == True):
        if (gray):
            gray_img = (gray_img - np.min(gray_img)) / (np.max(gray_img) -
                                                        np.min(gray_img))
        else:
            gray_img[:, :,
                     0] = (gray_img[:, :, 0] - np.mean(gray_img[:, :, 0])) / (
                         np.max(gray_img[:, :, 0]) -
                         np.mean(gray_img[:, :, 0]))
            gray_img[:, :,
                     1] = (gray_img[:, :, 1] - np.mean(gray_img[:, :, 1])) / (
                         np.max(gray_img[:, :, 1]) -
                         np.mean(gray_img[:, :, 1]))
            gray_img[:, :,
                     2] = (gray_img[:, :, 2] - np.mean(gray_img[:, :, 2])) / (
                         np.max(gray_img[:, :, 2]) -
                         np.mean(gray_img[:, :, 2]))
    if (denoising == True):
        gray_img = denoise_tv_chambolle(gray_img, weight=0.02)
    if (contouring == True):
        try:
            thresh = filters.threshold_minimum(gray_img)
        except RuntimeError:
            thresh = filters.threshold_otsu(gray_img)
        #print(np.mean(gray_img))
        gray_img = gray_img > thresh
    gray_img = gray_img.flatten()
    return gray_img
コード例 #23
0
def prepWhole(img):
    # type: (np.ndarray) -> Tuple[np.ndarray,np.ndarray,np.ndarray]
    # cv2.imshow('C',img)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    img = cv2.medianBlur(img, 5)
    cv2.imwrite('median.jpg', img)
    # cv2.imshow('G',img)
    # img = cv2.resize(img,(45,45),interpolation=cv2.INTER_CUBIC)
    # cv2.imshow('sz',img)
    adap = fl.threshold_minimum(img)
    print(adap)
    # if adap<127: adap=130
    temp, img = cv2.threshold(img, adap, 255, cv2.THRESH_BINARY_INV)

    # block_size = 35
    # adaptive_thresh = fl.threshold_local(img, block_size, offset=10)
    # img = 255*(img > adaptive_thresh)

    # img = cv2.adaptiveThreshold(img, 255, 1, 1, 11, 2)
    # blur = cv2.GaussianBlur(img, (5, 5), 0)
    # ret3, img = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
    # cv2.imshow('T',img)
    size = np.size(img)
    skel = np.zeros(img.shape, np.uint8)
    element = cv2.getStructuringElement(cv2.MORPH_CROSS, (3, 3))
    done = False
    # thresh = img
    img = cv2.dilate(img, None, iterations=3)
    img = cv2.erode(img, None, iterations=2)
    thresh = img
    edges = cv2.Canny(thresh, 100, 200)
    while (not done):
        eroded = cv2.erode(img, element)
        temp = cv2.dilate(eroded, element)
        temp = cv2.subtract(img, temp)
        skel = cv2.bitwise_or(skel, temp)
        img = eroded.copy()

        zeros = size - cv2.countNonZero(img)
        if zeros == size:
            done = True
    # skel=cv2.erode(skel,element)
    # cv2.imshow("skel", skel)
    # out=skel
    # skel = cv2.dilate(skel, None, iterations=3)
    # skel = cv2.erode(skel, None, iterations=2)
    # skel = cv2.medianBlur(skel, 5)
    # temp=1*(thresh>127)
    # skel = 255*skeletonize(temp)
    return skel, thresh, edges
コード例 #24
0
def get_binary(args, image, file: str, binpath: str) -> str:
    """
    Binarize image with different algorithms
    :param args:
    :param image:
    :param file:
    :param binpath:
    :return:
    """
    if not os.path.exists(binpath + file.split('/')[-1]):
        create_dir(binpath)
        uintimage = get_uintimg(image)
        if args.filter == "sauvola":
            thresh = imgfilter.threshold_sauvola(uintimage, args.threshwindow,
                                                 args.threshweight)
            binary = image > thresh
        elif args.filter == "niblack":
            thresh = imgfilter.threshold_niblack(uintimage, args.threshwindow,
                                                 args.threshweight)
            binary = thresh
        elif args.filter == "otsu":
            thresh = imgfilter.threshold_otsu(uintimage, args.threshbin)
            binary = image <= thresh
        elif args.filter == "yen":
            thresh = imgfilter.threshold_yen(uintimage, args.threshbin)
            binary = image <= thresh
        elif args.filter == "triangle":
            thresh = imgfilter.threshold_triangle(uintimage, args.threshbin)
            binary = image > thresh
        elif args.filter == "isodata":
            thresh = imgfilter.threshold_isodata(uintimage, args.threshbin)
            binary = image > thresh
        elif args.filter == "minimum":
            thresh = imgfilter.threshold_minimum(uintimage, args.threshbin,
                                                 args.threshitter)
            binary = image > thresh
        elif args.filter == "li":
            thresh = imgfilter.threshold_li(uintimage)
            binary = image > thresh
        elif args.filter == "mean":
            thresh = imgfilter.threshold_mean(uintimage)
            binary = image > thresh
        else:
            binary = uintimage
        with warnings.catch_warnings():
            # Transform rotate convert the img to float and save convert it back
            warnings.simplefilter("ignore")
            misc.imsave(binpath + file.split('/')[-1], binary)
    return binpath + file.split('/')[-1]
コード例 #25
0
def get_fov(img):
    im_s = img.size
    if max(im_s) > 500:
        img = Resize(500)(img)

    with np.errstate(divide='ignore'):
        im_v = equalize_adapthist(np.array(img))[:, :, 1]
        # im_v = equalize_adapthist(rgb2hsv(np.array(img))[:, :, 2])
    thresh = threshold_minimum(im_v)
    binary = binary_fill_holes(im_v > thresh)

    x0, y0, r = get_circ(binary)
    fov = create_circular_mask(binary.shape, center=(x0, y0), radius=r)

    return Resize(im_s[ : :-1])(Image.fromarray(fov))
コード例 #26
0
ファイル: preprocess.py プロジェクト: FranzSkuffka/maff
def binarize(image_abs_path):

    # Convert color image (3-channel deep) into grayscale (1-channel deep)
    # We reduce image dimensionality in order to remove unrelevant features like color.
    grayscale_img = imread(image_abs_path, as_grey=True)

    # Apply Gaussian Blur effect - this removes image noise
    gaussian_blur = gaussian(grayscale_img, sigma=1)

    # Apply minimum threshold
    thresh_sauvola = threshold_minimum(gaussian_blur)

    # Convert thresh_sauvola array values to either 1 or 0 (white or black)
    binary_img = gaussian_blur > thresh_sauvola

    return binary_img
コード例 #27
0
def binarize_curv(filter_img, im_name, output_path, save_img=False):
    """Binarizes the filtered output of the fibermorph.filter_curv function.

    Parameters
    ----------
    filter_img : np.ndarray
        Image after ridge filter (float64).
    im_name : str
        Image name.
    output_path : str or pathlib object
        Output directory path.
    save_img : bool
        True or false for saving image.

    Returns
    -------
    np.ndarray
        An array with the binarized image.

    """

    selem = skimage.morphology.disk(3)

    thresh_im = filter_img > threshold_minimum(filter_img)

    # clear the border of the image (buffer is the px width to be considered as border)
    cleared_im = skimage.segmentation.clear_border(thresh_im, buffer_size=10)

    # dilate the hair fibers
    binary_im = scipy.ndimage.binary_dilation(cleared_im,
                                              structure=selem,
                                              iterations=2)

    if save_img:
        output_path = make_subdirectory(output_path, append_name="binarized")
        # invert image
        save_im = skimage.util.invert(binary_im)

        # save image
        with pathlib.Path(output_path).joinpath(im_name +
                                                ".tiff") as save_name:
            im = Image.fromarray(save_im)
            im.save(save_name)
        return binary_im

    else:
        return binary_im
コード例 #28
0
ファイル: segptcls.py プロジェクト: jlaehne/ParticleSpy
def threshold(data, process_param):
    if process_param["threshold"] == "otsu":
        thresh = threshold_otsu(data)
    if process_param["threshold"] == "mean":
        thresh = threshold_mean(data)
    if process_param["threshold"] == "minimum":
        thresh = threshold_minimum(data)
    if process_param["threshold"] == "yen":
        thresh = threshold_yen(data)
    if process_param["threshold"] == "isodata":
        thresh = threshold_isodata(data)
    if process_param["threshold"] == "li":
        thresh = threshold_li(data)
    if process_param["threshold"] == "local":
        thresh = threshold_local(data, process_param["local_size"])
    if process_param["threshold"] == "local_otsu":
        selem = disk(process_param["local_size"])
        data = data.astype(np.float64)
        data = data - np.min(data)
        data = np.uint8(255 * data / np.max(data))
        thresh = rank.otsu(data, selem)
    if process_param["threshold"] == "lg_otsu":
        selem = disk(process_param["local_size"])
        data = data.astype(np.float64)
        data = data - np.min(data)
        data = np.uint8(255 * data / np.max(data))
        threshl = rank.otsu(data, selem)
        threshg = threshold_otsu(data)
    if process_param["threshold"] == "niblack":
        thresh = threshold_niblack(data, process_param["local_size"])
        mask = data > thresh
    if process_param["threshold"] == "sauvola":
        thresh = threshold_sauvola(data, process_param["local_size"])
        mask = data > thresh
    if process_param["threshold"] == "lg_otsu":
        mask1 = data >= threshl
        mask2 = data > threshg
        mask = mask1 * mask2
    elif process_param["threshold"] == "local_otsu":
        mask = data >= thresh
    else:
        mask = data > thresh

    labels = label(mask)

    return (labels)
コード例 #29
0
def vein_detection(OriginalImg, singleCellMask=[]):
    gray = skimage.color.rgb2gray(OriginalImg)

    if singleCellMask != []:
        thres = filters.threshold_minimum(gray)
        leaf_mask = ~(gray > thres)  #  plt. figure(),plt.imshow(leaf_mask)
        leaf_mask = morphology.binary_closing(
            leaf_mask, morphology.disk(2))  # remove small dark spots
    else:
        leaf_mask = generate_single_cellMask(OriginalImg)

    vein_image = -(gray * leaf_mask)
    imadjusted = exposure.rescale_intensity(vein_image)
    vein = feature.canny(imadjusted)

    vein = vein * 255
    return vein
コード例 #30
0
ファイル: img_processing.py プロジェクト: mehta-lab/pysero
def thresh_and_binarize(image_,
                        method='rosin',
                        invert=True,
                        min_size=10,
                        thr_percent=95):
    """
    receives greyscale np.ndarray image
        inverts the intensities
        thresholds on the minimum peak
        converts the image into binary about that threshold

    :param image_: np.ndarray
    :param method: str
        'bimodal' or 'unimodal'
    :return: spots threshold_min on this image
    """

    if invert:
        image_ = u.invert(image_)

    if method == 'bimodal':
        thresh = threshold_minimum(image_, nbins=512)

        spots = copy(image_)
        spots[image_ < thresh] = 0
        spots[image_ >= thresh] = 1

    elif method == 'otsu':
        spots = create_otsu_mask(image_, scale=1)

    elif method == 'rosin':
        spots = create_unimodal_mask(image_, str_elem_size=3)

    elif method == 'bright_spots':
        spots = image_ > np.percentile(image_, thr_percent)
        str_elem = disk(min_size)
        # spots = binary_closing(spots, str_elem)
        spots = binary_opening(spots, str_elem)
        spots = clear_border(spots)

    else:
        raise ModuleNotFoundError(
            "not a supported method for thresh_and_binarize")

    return spots
コード例 #31
0
plt.show()

######################################################################
# Bimodal histogram
# =================
#
# For pictures with a bimodal histogram, more specific algorithms can be used.
# For instance, the minimum algorithm takes a histogram of the image and smooths it
# repeatedly until there are only two peaks in the histogram.

from skimage.filters import threshold_minimum


image = data.camera()

thresh_min = threshold_minimum(image)
binary_min = image > thresh_min

fig, ax = plt.subplots(2, 2, figsize=(10, 10))

ax[0, 0].imshow(image, cmap=plt.cm.gray)
ax[0, 0].set_title('Original')

ax[0, 1].hist(image.ravel(), bins=256)
ax[0, 1].set_title('Histogram')

ax[1, 0].imshow(binary_min, cmap=plt.cm.gray)
ax[1, 0].set_title('Thresholded (min)')

ax[1, 1].hist(image.ravel(), bins=256)
ax[1, 1].axvline(thresh_min, color='r')
コード例 #32
0
# =================
#
# For pictures with a bimodal histogram, more specific algorithms can be used.
# For instance, the minimum algorithm takes a histogram of the image and smooths it
# repeatedly until there are only two peaks in the histogram. Then it
# finds the minimum value between the two peaks. After smoothing the
# histogram, there can be multiple pixel values with the minimum histogram
# count, so you can pick the 'min', 'mid', or 'max' of these values.
#

from skimage.filters import threshold_minimum


image = data.camera()

thresh_min = threshold_minimum(image, bias='min')
binary_min = image > thresh_min
thresh_mid = threshold_minimum(image, bias='mid')
binary_mid = image > thresh_mid
thresh_max = threshold_minimum(image, bias='max')
binary_max = image > thresh_max

fig, axes = plt.subplots(4, 2, figsize=(10, 10))
ax = axes.ravel()

ax[0].imshow(image, cmap=plt.cm.gray)
ax[0].set_title('Original')
ax[0].axis('off')

ax[1].hist(image.ravel(), bins=256)
ax[1].set_title('Histogram')