• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python skimage.img_as_ubyte函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: saver

    def saver(stepName, img, dbg=None, mode=mode):        
        path = (processedDir / str(imgName)).with_suffix(".{}.png".format(stepName) if stepName else ".png")
        
        if mode == 'cache' and processedDir and imgName:
            mode = 'save'
            if path.exists():
                print("Loading cached image:", path)
                img = ski.img_as_ubyte(io.imread(str(path)))
                mode = 'done'
            elif isinstance(img,type(None)):
                print("Caching image:", path)
                img = ski.img_as_ubyte(io.imread(str(imgName)))
            
        assert not isinstance(img,type(None))
        
        if mode == 'save' and processedDir and imgName:
            try:
                print("Saving:", img.shape, img.dtype, path.name, flush=True, )
                pil_img = PIL.Image.fromarray(img_as_ubyte(img))
                pil_img.save(str(path))
                if dbg:
                    dbg.saved_path = path
            except Exception as err:
                print("Error Saving:",path, err, flush=True, )

        elif mode == 'plot':
            plt.imshow(img)
            plt.suptitle(stepName+" "+imgName.name)
            plt.show(block=True)
            plt.close()

        return img
开发者ID:manasdas17,项目名称:scilab-2,代码行数:32,代码来源:image_measurements_auto.py


示例2: color_check

def color_check(plugin, fmt='png'):
    """Check roundtrip behavior for color images.

    All major input types should be handled as ubytes and read
    back correctly.
    """
    img = img_as_ubyte(data.chelsea())
    r1 = roundtrip(img, plugin, fmt)
    testing.assert_allclose(img, r1)

    img2 = img > 128
    r2 = roundtrip(img2, plugin, fmt)
    testing.assert_allclose(img2.astype(np.uint8), r2)

    img3 = img_as_float(img)
    r3 = roundtrip(img3, plugin, fmt)
    testing.assert_allclose(r3, img)

    img4 = img_as_int(img)
    if fmt.lower() in (('tif', 'tiff')):
        img4 -= 100
        r4 = roundtrip(img4, plugin, fmt)
        testing.assert_allclose(r4, img4)
    else:
        r4 = roundtrip(img4, plugin, fmt)
        testing.assert_allclose(r4, img_as_ubyte(img4))

    img5 = img_as_uint(img)
    r5 = roundtrip(img5, plugin, fmt)
    testing.assert_allclose(r5, img)
开发者ID:JeanKossaifi,项目名称:scikit-image,代码行数:30,代码来源:testing.py


示例3: _handle_input

def _handle_input(image, selem, out, mask, out_dtype=None):

    if image.dtype not in (np.uint8, np.uint16):
        image = img_as_ubyte(image)

    selem = np.ascontiguousarray(img_as_ubyte(selem > 0))
    image = np.ascontiguousarray(image)

    if mask is None:
        mask = np.ones(image.shape, dtype=np.uint8)
    else:
        mask = img_as_ubyte(mask)
        mask = np.ascontiguousarray(mask)

    if out is None:
        if out_dtype is None:
            out_dtype = image.dtype
        out = np.empty_like(image, dtype=out_dtype)

    if image is out:
        raise NotImplementedError("Cannot perform rank operation in place.")

    is_8bit = image.dtype in (np.uint8, np.int8)

    if is_8bit:
        max_bin = 255
    else:
        max_bin = max(4, image.max())

    bitdepth = int(np.log2(max_bin))
    if bitdepth > 10:
        warnings.warn("Bitdepth of %d may result in bad rank filter "
                      "performance due to large number of bins." % bitdepth)

    return image, selem, out, mask, max_bin
开发者ID:gmnamra,项目名称:scikit-image,代码行数:35,代码来源:generic.py


示例4: define_matrix

def define_matrix(image, number_of_iterations = 5000, termination_eps = 1e-10, warp = 'Affine'):

    warp_mode_dct = {
    'Translation' : cv2.MOTION_TRANSLATION,
    'Affine' : cv2.MOTION_AFFINE,
    'Euclidean' : cv2.MOTION_EUCLIDEAN,
    'Homography' : cv2.MOTION_HOMOGRAPHY
    }

    img = oib.image_reorder(image)

    color1 = img_as_ubyte(img[0,0,:,:,0])
    color2 = img_as_ubyte(img[0,0,:,:,1])

    warp_mode = warp_mode_dct.pop('%s' % warp)

    if warp_mode == cv2.MOTION_HOMOGRAPHY :
        warp_matrix = np.eye(3, 3, dtype=np.float32)
    else :
        warp_matrix = np.eye(2, 3, dtype=np.float32)

    number_of_iterations = number_of_iterations
    termination_eps = termination_eps
    criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, number_of_iterations,  termination_eps)

    (cc, warp_matrix) = cv2.findTransformECC (color1,color2,warp_matrix, warp_mode, criteria)

    return warp_matrix
开发者ID:cespenel,项目名称:image_processing,代码行数:28,代码来源:ImageAlignment.py


示例5: worker

def worker(input_file_path, queue):
    int_values = []
    path_sections = input_file_path.split("/")

    for string in path_sections:
        if re.search(r'\d+', string) is not None:
            int_values.append(int(re.search(r'\d+', string).group()))

    file_count = int_values[-1]

    image = cv2.imread(input_file_path, cv2.CV_LOAD_IMAGE_GRAYSCALE)
    edges = img_as_ubyte(canny(image, sigma=canny_sigma))
    img_bw = cv2.threshold(edges, 250, 255, cv2.THRESH_BINARY)[1]

    point = _find_bottom_edge(img_bw)

    try:
        distance = len(img_bw) - point[1]
    except TypeError:
        try:
            edges = img_as_ubyte(canny(image, sigma=canny_sigma_closeup))
            img_bw = cv2.threshold(edges, 250, 255, cv2.THRESH_BINARY)[1]

            distance = len(img_bw) - point[1]
        except TypeError:
            distance = 0

    output = str(file_count) + ":" + str(distance) + "\n"
    queue.put(output)

    return output
开发者ID:agupta231,项目名称:Feature-Tracker,代码行数:31,代码来源:distance_compute_write_to_file.py


示例6: _apply

def _apply(func8, func16, image, selem, out, mask, shift_x, shift_y):
    selem = img_as_ubyte(selem > 0)
    image = np.ascontiguousarray(image)

    if mask is None:
        mask = np.ones(image.shape, dtype=np.uint8)
    else:
        mask = np.ascontiguousarray(mask)
        mask = img_as_ubyte(mask)

    if image is out:
        raise NotImplementedError("Cannot perform rank operation in place.")

    is_8bit = image.dtype in (np.uint8, np.int8)

    if func8 is not None and (is_8bit or func16 is None):
        out = _apply8(func8, image, selem, out, mask, shift_x, shift_y)
    else:
        image = img_as_uint(image)
        if out is None:
            out = np.zeros(image.shape, dtype=np.uint16)
        bitdepth = find_bitdepth(image)
        if bitdepth > 11:
            image = image >> 4
            bitdepth = find_bitdepth(image)
        func16(image, selem, shift_x=shift_x, shift_y=shift_y, mask=mask,
               bitdepth=bitdepth + 1, out=out)

    return out
开发者ID:RONNCC,项目名称:scikit-image,代码行数:29,代码来源:_rank.py


示例7: dilation

def dilation(image, selem=None, out=None, shift_x=False, shift_y=False):
    """Return greyscale morphological dilation of an image.

    Morphological dilation sets a pixel at (i,j) to the maximum over all pixels
    in the neighborhood centered at (i,j). Dilation enlarges bright regions
    and shrinks dark regions.

    Parameters
    ----------

    image : ndarray
        Image array.
    selem : ndarray, optional
        The neighborhood expressed as a 2-D array of 1's and 0's.
        If None, use cross-shaped structuring element (connectivity=1).
    out : ndarray, optional
        The array to store the result of the morphology. If None, is
        passed, a new array will be allocated.
    shift_x, shift_y : bool, optional
        shift structuring element about center point. This only affects
        eccentric structuring elements (i.e. selem with even numbered sides).

    Returns
    -------
    dilated : uint8 array
        The result of the morphological dilation.

    Notes
    -----
    For `uint8` (and `uint16` up to a certain bit-depth) data, the lower
    algorithm complexity makes the `skimage.filter.rank.maximum` function more
    efficient for larger images and structuring elements.

    Examples
    --------
    >>> # Dilation enlarges bright regions
    >>> import numpy as np
    >>> from skimage.morphology import square
    >>> bright_pixel = np.array([[0, 0, 0, 0, 0],
    ...                          [0, 0, 0, 0, 0],
    ...                          [0, 0, 1, 0, 0],
    ...                          [0, 0, 0, 0, 0],
    ...                          [0, 0, 0, 0, 0]], dtype=np.uint8)
    >>> dilation(bright_pixel, square(3))
    array([[0, 0, 0, 0, 0],
           [0, 1, 1, 1, 0],
           [0, 1, 1, 1, 0],
           [0, 1, 1, 1, 0],
           [0, 0, 0, 0, 0]], dtype=uint8)

    """

    if image is out:
        raise NotImplementedError("In-place dilation not supported!")

    image = img_as_ubyte(image)
    selem = img_as_ubyte(selem)
    return cmorph._dilate(image, selem, out=out,
                          shift_x=shift_x, shift_y=shift_y)
开发者ID:JeanKossaifi,项目名称:scikit-image,代码行数:59,代码来源:grey.py


示例8: preprocess

def preprocess(filename):
    image = img_as_ubyte(io.imread(filename, as_grey = True))

    if image.shape[0] != 768:
        print(image.shape)
        print("WARN: Resizing image to old iPad Size. TODO> Move forward to retina images!")
        return img_as_ubyte(transform.resize(image, (768, 1024)))

    return image
开发者ID:blmarket,项目名称:CoCParser,代码行数:9,代码来源:parse.py


示例9: test_threshold_minimum

def test_threshold_minimum():
    camera = skimage.img_as_ubyte(data.camera())

    threshold = threshold_minimum(camera)
    assert_equal(threshold, 76)

    astronaut = skimage.img_as_ubyte(data.astronaut())
    threshold = threshold_minimum(astronaut)
    assert_equal(threshold, 114)
开发者ID:andreydung,项目名称:scikit-image,代码行数:9,代码来源:test_thresholding.py


示例10: dynamic_masking

def dynamic_masking(image,method='edges',filter_size=7,threshold=0.005):
    """ Dynamically masks out the objects in the PIV images
    
    Parameters
    ----------
    image: image
        a two dimensional array of uint16, uint8 or similar type
        
    method: string
        'edges' or 'intensity':
        'edges' method is used for relatively dark and sharp objects, with visible edges, on 
        dark backgrounds, i.e. low contrast
        'intensity' method is useful for smooth bright objects or dark objects or vice versa, 
        i.e. images with high contrast between the object and the background
    
    filter_size: integer
        a scalar that defines the size of the Gaussian filter
    
    threshold: float
        a value of the threshold to segment the background from the object
        default value: None, replaced by sckimage.filter.threshold_otsu value
            
    Returns
    -------
    image : array of the same datatype as the incoming image with the object masked out
        as a completely black region(s) of zeros (integers or floats).
    
    
    Example
    --------
    frame_a  = openpiv.tools.imread( 'Camera1-001.tif' )
    imshow(frame_a) # original
    
    frame_a = dynamic_masking(frame_a,method='edges',filter_size=7,threshold=0.005)
    imshow(frame_a) # masked 
        
    """
    imcopy = np.copy(image)
    # stretch the histogram
    image = exposure.rescale_intensity(img_as_float(image), in_range=(0, 1))
    # blur the image, low-pass
    blurback = img_as_ubyte(gaussian_filter(image,filter_size))
    if method is 'edges':
        # identify edges
        edges = sobel(blurback)
        blur_edges = gaussian_filter(edges,21)
        # create the boolean mask 
        bw = (blur_edges > threshold)
        bw = img_as_ubyte(binary_fill_holes(bw))
        imcopy -= blurback
        imcopy[bw] = 0.0
    elif method is 'intensity':
        background = gaussian_filter(median_filter(image,filter_size),filter_size)
        imcopy[background > threshold_otsu(background)] = 0

        
    return imcopy #image
开发者ID:OpenPIV,项目名称:openpiv-python,代码行数:57,代码来源:preprocess.py


示例11: test_divide_and_reassemble

 def test_divide_and_reassemble(self):
     pic = img_as_ubyte(io.imread("./kitteh.jpg"))
     pic = resize(pic, (500,500), mode='nearest')
     pic = img_as_ubyte(pic)
     print "size "+str(pic.shape)
     for shape in [(10,10),(10,20),(30,30),(33,48)]:
         print shape
         parts = divide_into_parts(pic,*shape)
         pic2 = assemble_from_parts(parts, False, False)
         self.assertTrue((pic==pic2).all())
开发者ID:carolinux,项目名称:mosaic,代码行数:10,代码来源:util_tests.py


示例12: open_image

def open_image(address):
    image = imread(address)
    gray_image = rgb2gray(image)
    r = image[:,:,0]
    g = image[:,:,1]
    b = image[:,:,2]
#    
#    m,n,_ = image.shape
#
#    gray_image = img_as_ubyte(gray_image)
    
    return img_as_ubyte(gray_image), img_as_ubyte(r), img_as_ubyte(g), img_as_ubyte(b)
开发者ID:mehdi1902,项目名称:SarBeh,代码行数:12,代码来源:segmentation.py


示例13: test_threshold_minimum

def test_threshold_minimum():
    camera = skimage.img_as_ubyte(data.camera())

    threshold = threshold_minimum(camera)
    assert threshold == 76

    threshold = threshold_minimum(camera, bias='max')
    assert threshold == 77

    astronaut = skimage.img_as_ubyte(data.astronaut())
    threshold = threshold_minimum(astronaut)
    assert threshold == 117
开发者ID:Gildus,项目名称:scikit-image,代码行数:12,代码来源:test_thresholding.py


示例14: load_disp_image

 def load_disp_image(self, img_name,j,display_only=False):
     print ("Setting image: %s" % str(img_name))
     try:
         temp_img = img_as_ubyte(imread(img_name))
     except:
         print("Error reading file, setting zero image")
         h_img=self.exp1.active_params.m_params.imx
         v_img=self.exp1.active_params.m_params.imy
         temp_img = img_as_ubyte(np.zeros((h_img,v_img)))
     if not display_only:
         ptv.py_set_img(temp_img,j)
     if len(temp_img)>0:
         self.camera_list[j].update_image(temp_img)
开发者ID:OpenPTV,项目名称:openptv-python,代码行数:13,代码来源:pyptv_gui.py


示例15: dilation

def dilation(image, selem, out=None, shift_x=False, shift_y=False):
    """Return greyscale morphological dilation of an image.

    Morphological dilation sets a pixel at (i,j) to the maximum over all pixels
    in the neighborhood centered at (i,j). Dilation enlarges bright regions
    and shrinks dark regions.

    Parameters
    ----------

    image : ndarray
        Image array.
    selem : ndarray
        The neighborhood expressed as a 2-D array of 1's and 0's.
    out : ndarray
        The array to store the result of the morphology. If None, is
        passed, a new array will be allocated.
    shift_x, shift_y : bool
        shift structuring element about center point. This only affects
        eccentric structuring elements (i.e. selem with even numbered sides).

    Returns
    -------
    dilated : uint8 array
        The result of the morphological dilation.

    Examples
    --------
    >>> # Dilation enlarges bright regions
    >>> import numpy as np
    >>> from skimage.morphology import square
    >>> bright_pixel = np.array([[0, 0, 0, 0, 0],
    ...                          [0, 0, 0, 0, 0],
    ...                          [0, 0, 1, 0, 0],
    ...                          [0, 0, 0, 0, 0],
    ...                          [0, 0, 0, 0, 0]], dtype=np.uint8)
    >>> dilation(bright_pixel, square(3))
    array([[0, 0, 0, 0, 0],
           [0, 1, 1, 1, 0],
           [0, 1, 1, 1, 0],
           [0, 1, 1, 1, 0],
           [0, 0, 0, 0, 0]], dtype=uint8)

    """

    if image is out:
        raise NotImplementedError("In-place dilation not supported!")
    image = img_as_ubyte(image)
    selem = img_as_ubyte(selem)
    return cmorph._dilate(image, selem, out=out,
                          shift_x=shift_x, shift_y=shift_y)
开发者ID:A-0-,项目名称:scikit-image,代码行数:51,代码来源:grey.py


示例16: noise_reduction

def noise_reduction(image, background, window_size = 5, mode = 0):
	#  GrayScale image use mode = 0
	#  mode = 0: dealing RGB image with each channel 
	#  mode!= 0: dealing RGB image with HSV value 
	if(mode == 0):
		med_image = median_each(image, disk(window_size))
		med_bckg  = median_each(background, disk(window_size))

	else :
		med_image = img_as_ubyte(median_hsv(image, disk(window_size)))
		med_bckg  = img_as_ubyte(median_hsv(background, disk(window_size)))

	norm_image = np.true_divide(med_image, (med_bckg/255*254+1))/255	
	return norm_image
开发者ID:UIUC-SULLIVAN,项目名称:bubble-counting,代码行数:14,代码来源:preprocessing.py


示例17: _merge_images

def _merge_images(img_top, img_bottom, mask=0):
    """
    Function to combine two images with mask by replacing all pixels of img_bottom which
    equals to mask by pixels from img_top.

    :param img_top: greyscale image which will replace masked pixels
    :param img_bottom: greyscale image which pixels will be replace
    :param mask: pixel value to be used as mask (int)
    :return: combined greyscale image
    """
    img_top = skimage.img_as_ubyte(img_top)
    img_bottom = skimage.img_as_ubyte(img_bottom)
    merge_layer = img_top == mask
    img_top[merge_layer] = img_bottom[merge_layer]
    return img_top
开发者ID:marsbroshok,项目名称:face-replace,代码行数:15,代码来源:faceWarp.py


示例18: get_textural_features

def get_textural_features(img, isMultidirectional=False, distance=1):
    '''Extract GLCM feature vector from image
    Args:
        img: input image.

        isMultidirectional: Controls whether co-occurence should be calculated
            in other directions (ie 45 degrees, 90 degrees and 135 degrees).

        distance: Distance between pixels for co-occurence.

    Returns:
        features: if isMultidirectional=False, this is a 4 element vector of
        [dissimilarity, correlation,homogeneity, energy]. If not it is a 16
        element vector containing each of the above properties in each direction.
    '''
    if(isMultidirectional):
        img = img_as_ubyte(rgb2gray(img))
        glcm = greycomatrix(img, [distance], [0, 0.79, 1.57, 2.36], 256, symmetric=True, normed=True)
        dissimilarity_1 = greycoprops(glcm, 'dissimilarity')[0][0]
        dissimilarity_2 = greycoprops(glcm, 'dissimilarity')[0][1]
        dissimilarity_3 = greycoprops(glcm, 'dissimilarity')[0][2]
        dissimilarity_4 = greycoprops(glcm, 'dissimilarity')[0][3]
        correlation_1 = greycoprops(glcm, 'correlation')[0][0]
        correlation_2 = greycoprops(glcm, 'correlation')[0][1]
        correlation_3 = greycoprops(glcm, 'correlation')[0][2]
        correlation_4 = greycoprops(glcm, 'correlation')[0][3]
        homogeneity_1 = greycoprops(glcm, 'homogeneity')[0][0]
        homogeneity_2 = greycoprops(glcm, 'homogeneity')[0][1]
        homogeneity_3 = greycoprops(glcm, 'homogeneity')[0][2]
        homogeneity_4 = greycoprops(glcm, 'homogeneity')[0][3]
        energy_1 = greycoprops(glcm, 'energy')[0][0]
        energy_2 = greycoprops(glcm, 'energy')[0][1]
        energy_3 = greycoprops(glcm, 'energy')[0][2]
        energy_4 = greycoprops(glcm, 'energy')[0][3]
        feature = np.array([dissimilarity_1, dissimilarity_2, dissimilarity_3,\
         dissimilarity_4, correlation_1, correlation_2, correlation_3, correlation_4,\
         homogeneity_1, homogeneity_2, homogeneity_3, homogeneity_4, energy_1,\
         energy_2, energy_3, energy_4])
        return feature
    else:
        img = img_as_ubyte(rgb2gray(img))
        glcm = greycomatrix(img, [distance], [0], 256, symmetric=True, normed=True)
        dissimilarity = greycoprops(glcm, 'dissimilarity')[0][0]
        correlation = greycoprops(glcm, 'correlation')[0][0]
        homogeneity = greycoprops(glcm, 'homogeneity')[0][0]
        energy = greycoprops(glcm, 'energy')[0][0]
        feature = np.array([dissimilarity, correlation, homogeneity, energy])
        return feature
开发者ID:oduwa,项目名称:Wheat-Count,代码行数:48,代码来源:Helper.py


示例19: test_equalize_ubyte

def test_equalize_ubyte():
    with expected_warnings(['precision loss']):
        img = skimage.img_as_ubyte(test_img)
    img_eq = exposure.equalize_hist(img)

    cdf, bin_edges = exposure.cumulative_distribution(img_eq)
    check_cdf_slope(cdf)
开发者ID:ameya005,项目名称:scikit-image,代码行数:7,代码来源:test_exposure.py


示例20: __init__

    def __init__(self, path=None, array=None, xy_array=None):
        self._modified = False
        self.scale = 1
        self._path = None
        self._format = None

        n_args = len([a for a in [path, array, xy_array] if a is not None])
        if n_args != 1:
            msg = "Must provide a single keyword arg (path, array, xy_array)."
            ValueError(msg)
        elif path is not None:
            if not is_url(path):
                path = os.path.abspath(path)
            self._path = path
            with file_or_url_context(path) as context:
                self.array = img_as_ubyte(io.imread(context))
                self._format = imghdr.what(context)
        elif array is not None:
            self.array = array
        elif xy_array is not None:
            self.xy_array = xy_array

        # Force RGBA internally (use max alpha)
        if self.array.shape[-1] == 3:
            self.array = np.insert(self.array, 3, values=255, axis=2)
开发者ID:haohao200609,项目名称:Hybrid,代码行数:25,代码来源:_novice.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python skimage.img_as_uint函数代码示例发布时间:2022-05-27
下一篇:
Python skimage.img_as_float函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap