当前位置: 首页>>代码示例>>Python>>正文


Python filter.threshold_adaptive函数代码示例

本文整理汇总了Python中skimage.filter.threshold_adaptive函数的典型用法代码示例。如果您正苦于以下问题:Python threshold_adaptive函数的具体用法?Python threshold_adaptive怎么用?Python threshold_adaptive使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了threshold_adaptive函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: run_cmd

def run_cmd(method, block_size=40):
    stdin = sys.stdin.read()
    if stdin == '\n':
        exit()

    img = Image.open(StringIO.StringIO(stdin)).convert('L')
    imgc = np.array(img)

    imggray = rgb2gray(imgc)

    if method is None or method == '':
        imgthresh = threshold_adaptive(imggray, block_size, 'gaussian', offset=10)
    elif method == 'gaussian':
        imgthresh = threshold_adaptive(imggray, block_size, 'gaussian', offset=10)
    elif method == 'median':
        imgthresh = threshold_adaptive(imggray, block_size, 'median', offset=10)
    elif method == 'mean':
        imgthresh = threshold_adaptive(imggray, block_size, 'mean', offset=10)
    elif method == 'otsu':
        thresh = threshold_otsu(imggray)
        imgthresh = imggray > thresh
    elif method == 'yen':
        thresh = threshold_yen(imggray)
        imgthresh = imggray > thresh
    elif method == 'iso':
        thresh = threshold_isodata(imggray)
        imgthresh = imggray > thresh


    rescaled = (255.0 / imgthresh.max() * (imgthresh - imgthresh.min())).astype(np.uint8)

    out = Image.fromarray(rescaled)
    out.save(sys.stdout, format='PNG')
开发者ID:CircaVictor,项目名称:FCC-Political-Ads_The-Code,代码行数:33,代码来源:threshold.py

示例2: modify

def modify(img):
    """Randomly modify an image
    
    This is a preprocessing step for training an OCR classifier. It takes
    in an image and casts it to greyscale, reshapes it, and adds some
    (1) rotations, (2) translations and (3) noise.
    
    If more efficiency is needed, we could factor out some of the initial
    nonrandom transforms.
    """
    
    block_size = np.random.uniform(20, 40)
    rotation = 5*np.random.randn()
    
    #print 'BLOCK SIZE', block_size
    #print 'ROTATION  ', rotation
    
    img = color.rgb2grey(img)
    img = transform.resize(img, output_shape=(50,30))
    img = filter.threshold_adaptive(img, block_size=block_size)
    
    # rotate the image
    img = np.logical_not(transform.rotate(np.logical_not(img), rotation))
    # translate the image
    img = shift(img)
    # add some noise to the image
    img = noise(img)
    
    img = transform.resize(img, output_shape=(25,15))
    return filter.threshold_adaptive(img, block_size=25)
开发者ID:rmcgibbo,项目名称:autogert,代码行数:30,代码来源:train_synthetic.py

示例3: sino_remove_bragg_spots

def sino_remove_bragg_spots(sinogram, block_size=5, tolerance=0.05, sensitivity_low=1.5, sensitivity_high=0.2):
    """ If value is above some local threshold,
        replace by median. Removes dodgy highlights and shadows
        resulting from bragg peaks from large crystallites
        in diffracting orientations """

    # Footprint for median value to replace bragg spots.
    # Usually the spots are contained to one projection,
    # so we sample above and below for good values.
    footprint = np.array(
        [[  False, True, False ],
         [  True,  True,  True ],
         [  False, False, False ],
         [  True,  True,  True ],
         [  False, True, False ]])

    # Only consider pixels which differ from the local median by this offset.
    # Highlights and shadows will skew the arithmetic mean so use median.

    median_value = np.median(sinogram)
    offset_high  = np.median(sinogram[sinogram>median_value])
    offset_low   = np.median(sinogram[sinogram<median_value])

    utils.debug_print(median=median_value,offset_high=offset_high, offset_low=offset_low)

    mask_low = ~filters.threshold_adaptive(
                 sinogram,
                 block_size,
                 method='median',
                 offset=-sensitivity_low*(offset_low-median_value),
             )
    mask_high = filters.threshold_adaptive(
                 sinogram,
                 block_size,
                 method='median',
                 offset=-sensitivity_high*(offset_high-median_value),
             )
    if float(mask_high.sum()) > tolerance * mask_high.size:
        # Too many values marked as spots. Ignoring hilights.
        print('Found more than %s%% of values as hilights' % (tolerance * 100))
        mask_high = np.zeros(shape=sinogram.shape, dtype=bool)
    if float(mask_low.sum()) > tolerance * mask_low.size:
        # Too many values marked as spots. Ignoring shadows.
        print('Found more than %s%% of values as shadows' % (tolerance * 100))
        mask_low = np.zeros(shape=sinogram.shape, dtype=bool)

    mask = mask_low + mask_high
    # FIXME, only calculate values in mask.
    median = ndimage.median_filter(sinogram, footprint=footprint)
    ret = sinogram.copy()
    ret[mask==True] = median[mask==True]
    return ret
开发者ID:amundhov,项目名称:xrdtoolkit,代码行数:52,代码来源:tomo.py

示例4: segment

    def segment(self, src):
        image = src.ndarray[:]
        if self.use_adaptive_threshold:
            block_size = 25
            markers = threshold_adaptive(image, block_size) * 255
            markers = invert(markers)

        else:
            markers = zeros_like(image)
            markers[image < self.threshold_low] = 1
            markers[image > self.threshold_high] = 255

        elmap = sobel(image, mask=image)
        wsrc = watershed(elmap, markers, mask=image)

#        elmap = ndimage.distance_transform_edt(image)
#        local_maxi = is_local_maximum(elmap, image,
#                                      ones((3, 3))
#                                      )
#        markers = ndimage.label(local_maxi)[0]
#        wsrc = watershed(-elmap, markers, mask=image)
#        fwsrc = ndimage.binary_fill_holes(out)
#        return wsrc
        if self.use_inverted_image:
            out = invert(wsrc)
        else:
            out = wsrc

#        time.sleep(1)
#        do_later(lambda:self.show_image(image, -elmap, out))
        return out
开发者ID:softtrainee,项目名称:arlab,代码行数:31,代码来源:region.py

示例5: intensity_object_features

def intensity_object_features(im, adaptive_t_radius=51, sample_size=None):
    """Segment objects based on intensity threshold and compute properties.

    Parameters
    ----------
    im : 2D np.ndarray of float or uint8.
        The input image.
    adaptive_t_radius : int, optional
        The radius to calculate background with adaptive threshold.
    sample_size : int, optional
        Sample this many objects randomly, rather than measuring all
        objects.

    Returns
    -------
    f : 1D np.ndarray of float
        The feature vector.
    names : list of string
        The list of feature names.
    """
    tim1 = im > imfilter.threshold_otsu(im)
    f1, names1 = object_features(tim1, im, sample_size=sample_size)
    names1 = ['otsu-threshold-' + name for name in names1]
    tim2 = imfilter.threshold_adaptive(im, adaptive_t_radius)
    f2, names2 = object_features(tim2, im, sample_size=sample_size)
    names2 = ['adaptive-threshold-' + name for name in names2]
    f = np.concatenate([f1, f2])
    return f, names1 + names2
开发者ID:gitter-badger,项目名称:husc,代码行数:28,代码来源:features.py

示例6: segment

    def segment(self, src):
        '''
            pychron: preprocessing cv.Mat
        '''
#        image = pychron.ndarray[:]
#         image = asarray(pychron)
        image = src[:]
        if self.use_adaptive_threshold:
#            block_size = 25
            markers = threshold_adaptive(image, self.block_size)

            n = markers[:].astype('uint8')
            n[markers == True] = 255
            n[markers == False] = 1
            markers = n

        else:
            markers = zeros_like(image)
            markers[image < self.threshold_low] = 1
            markers[image > self.threshold_high] = 255

        elmap = sobel(image, mask=image)
        wsrc = watershed(elmap, markers, mask=image)

#         wsrc = wsrc.astype('uint8')
        return invert(wsrc)
开发者ID:OSUPychron,项目名称:pychron,代码行数:26,代码来源:region.py

示例7: __call__

    def __call__(self, image, window_size=10, threshold=0, fill_holes=True,
                 outline_smoothing=2, remove_borderobjects=True, size_min=1,
                 *args, **kw):

        thresh = threshold_adaptive(image, block_size=window_size,
                                    offset=-1*threshold)

        if outline_smoothing >= 1:
            thresh = outlineSmoothing(thresh, outline_smoothing)

        thresh = remove_small_objects(thresh, size_min)

        seeds = ndi.label(clear_border(~thresh))[0]
        thresh = ndi.binary_fill_holes(thresh)
        smask = seeds.astype(bool)

        # object don't touch border after outline smoothing
        if remove_borderobjects:
            thresh = clear_border(thresh)

        img = np.zeros(thresh.shape)
        img[~smask] = 1
        edt = ndi.morphology.distance_transform_edt(img)
        edt -= ndi.morphology.distance_transform_edt(seeds)

        labels = watershed(edt, seeds)
        labels[smask] = 0
        labels[~thresh] = 0

        return labels
开发者ID:rhoef,项目名称:afw,代码行数:30,代码来源:honeycomp.py

示例8: adaptive_segment

def adaptive_segment(args):
    """
    Applies an adaptive threshold to reconstructed data.

    Also known as local or dynamic thresholding
    where the threshold value is the weighted mean
    for the local neighborhood of a pixel subtracted
    by constant. Alternatively the threshold can be
    determined dynamically by a given function using
    the 'generic' method.

    Parameters
    ----------
    data : ndarray, float32
        3-D reconstructed data with dimensions:
        [slices, pixels, pixels]

    block_size : scalar, int
        Uneven size of pixel neighborhood which is
        used to calculate the threshold value
        (e.g. 3, 5, 7, ..., 21, ...).

    offset : scalar, float
         Constant subtracted from weighted mean of
         neighborhood to calculate the local threshold
         value. Default offset is 0.

    Returns
    -------
    output : ndarray
        Thresholded data.

    References
    ----------
    - `http://scikit-image.org/docs/dev/auto_examples/plot_threshold_adaptive.html \
    <http://scikit-image.org/docs/dev/auto_examples/plot_threshold_adaptive.html>`_
    """
    # Arguments passed by multi-processing wrapper
    ind, dshape, inputs = args

    # Function inputs
    data = mp.tonumpyarray(mp.shared_arr, dshape)  # shared-array
    block_size, offset = inputs

    for m in ind:
        img = data[m, :, :]

        # Perform scikit adaptive thresholding.
        img = threshold_adaptive(img, block_size=block_size, offset=offset)

        # Remove small white regions
        img = ndimage.binary_opening(img)

        # Remove small black holes
        img = ndimage.binary_closing(img)

        data[m, :, :] = img
开发者ID:djvine,项目名称:tomopy,代码行数:57,代码来源:adaptive_segment.py

示例9: adapative_threshold

def adapative_threshold(image, block_size=100):
	"""
	This method returns the adaptively-thresholded image.
	"""

	thresholded_image = threshold_adaptive(image, block_size)
	imshow(thresholded_image)

	return thresholded_image
开发者ID:runstadler-lab,项目名称:Seal-H3N8-Image-Analysis,代码行数:9,代码来源:rgprocessing.py

示例10: extract_bill

def extract_bill(image, screen, ratio):
    """"Extract the bill of the image"""
    warped = four_point_transform(image, screen.reshape(4, 2) * ratio)

    # convert the warped image to grayscale, then threshold it
    # to give it that 'black and white' paper effect
    warped = cv2.cvtColor(warped, cv2.COLOR_BGR2GRAY)
    warped = threshold_adaptive(warped, 250, offset=10)
    warped = warped.astype("uint8") * 255
    return warped
开发者ID:llrs,项目名称:bills,代码行数:10,代码来源:process_image.py

示例11: scan

    def scan(cls, filepath):
        print("Starting scan")
        # load the image and compute the ratio of the old height
        # to the new height, clone it, and resize it
        image = cv2.imread(filepath)
        ratio = image.shape[0] / 500.0
        orig = image.copy()
        image = imutils.resize(image, height=500)

        # convert the image to grayscale, blur it, and find edges
        # in the image
        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        gray = cv2.GaussianBlur(gray, (5, 5), 0)
        edged = cv2.Canny(gray, 75, 200)

        # find the contours in the edged image, keeping only the
        # largest ones, and initialize the screen contour
        cnts, hierarchy = cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
        cnts = sorted(cnts, key=cv2.contourArea, reverse=True)[:5]
        screenCnt = None

        # loop over the contours
        for c in cnts:
            # approximate contours
            peri = cv2.arcLength(c, True)
            approx = cv2.approxPolyDP(c, 0.02 * peri, True)

            # if our approximated contour has four points, then we
            # can assume that we have found our screen
            if len(approx) == 4:
                screenCnt = approx
                break

        # Check if we found a 4 point contour. If not, we create our own bounding box
        # with the largest contour
        if screenCnt is None:
            height, width, channels = image.shape
            imageBounds = np.array([[1, 1], [width, 1], [width, height], [1, height]])
            screenCnt = imutils.get_bounding_box(imageBounds)

        # apply the four point transform to obtain a top-down
        # view of the original image
        warped = four_point_transform(orig, screenCnt.reshape(4, 2) * ratio)

        # convert the warped image to grayscale, then threshold it
        # to give it that 'black and white' paper effect
        warped = cv2.cvtColor(warped, cv2.COLOR_BGR2GRAY)
        warped = threshold_adaptive(warped, 250, offset=10)
        warped = warped.astype("uint8") * 255

        # Write out image to tmp file
        filename = "tmp/tmp-result.png"
        cv2.imwrite(filename, warped)
        print("Finished scan")
        return filename
开发者ID:twuster,项目名称:DocumentScanner,代码行数:55,代码来源:scanner.py

示例12: preprocess

def preprocess(image, height=50, block_size=50):
    """Turn to greyscale, scale to a height, and then threshold to binary
    """

    image = color.rgb2grey(image)
    size_factor = float(height) / image.shape[0]
    new_size = [int(e * size_factor) for e in image.shape]
    image = transform.resize(image, new_size)
    image = filter.threshold_adaptive(image, block_size=30)

    return image
开发者ID:rmcgibbo,项目名称:autogert,代码行数:11,代码来源:image.py

示例13: image_features_resize_adaptive

def image_features_resize_adaptive(img, maxPixel, num_features,imageSize):
     # X is the feature vector with one row of features per image
     #  consisting of the pixel values a, num_featuresnd our metric
     block_size = 20
     im = threshold_adaptive(img, block_size, offset=5)
     X=np.zeros(num_features, dtype=float)
     image = resize(im, (maxPixel, maxPixel))
     # Store the rescaled image pixels
     X[0:imageSize] = np.reshape(image,(1, imageSize))

     return X
开发者ID:kailex,项目名称:Bowl,代码行数:11,代码来源:Prepare_Features.py

示例14: thresholdImage

 def thresholdImage(self):
     """Threshold Image"""
     ### THRESHOLDING ###
     #=======================================================================
     # self.ThresholdMethod:
     # thresholdGlobalOtsu = filter.threshold_otsu(pyLaneTracker.Img, 64)
     # thresholdGlobalYen = filter.threshold_yen(pyLaneTracker.Img, 64)
     #=======================================================================
     
     thresholdAdaptive = filter.threshold_adaptive(self.Img, 96, method='median', offset=0, mode='reflect', param=None)
     self.Threshold = thresholdAdaptive
开发者ID:janthonywilson,项目名称:Cruise,代码行数:11,代码来源:pyCar.py

示例15: image_features_hog2

def image_features_hog2(img, num_features,orientation,maxcell,maxPixel):
     # X is the feature vector with one row of features per image
     #  consisting of the pixel values a, num_featuresnd our metric
     block_size = 10
     image = threshold_adaptive(img, block_size, offset=5)
     im = resize(image, (maxPixel, maxPixel))
     ##hog scikit transform
     fd= hog(im, orientations=orientation, pixels_per_cell=(maxcell, maxcell),
                    cells_per_block=(1, 1), visualise=False,normalise=True)

     return fd
开发者ID:kailex,项目名称:Bowl,代码行数:11,代码来源:Prepare_Features.py


注:本文中的skimage.filter.threshold_adaptive函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。