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


Python skimage.img_as_ubyte方法代码示例

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


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

示例1: resize_image

# 需要导入模块: import skimage [as 别名]
# 或者: from skimage import img_as_ubyte [as 别名]
def resize_image(img, new_size_typle, resize_method):
    try:
        from skimage import img_as_ubyte
        from skimage.transform import resize
    except ImportError:
        logger.error(
            ' scikit-image is not installed. '
            'In order to install all image feature dependencies run '
            'pip install ludwig[image]'
        )
        sys.exit(-1)

    if tuple(img.shape[:2]) != new_size_typle:
        if resize_method == CROP_OR_PAD:
            return crop_or_pad(img, new_size_typle)
        elif resize_method == INTERPOLATE:
            return img_as_ubyte(resize(img, new_size_typle))
        raise ValueError(
            'Invalid image resize method: {}'.format(resize_method))
    return img 
开发者ID:uber,项目名称:ludwig,代码行数:22,代码来源:image_utils.py

示例2: main

# 需要导入模块: import skimage [as 别名]
# 或者: from skimage import img_as_ubyte [as 别名]
def main():
  parser = argparse.ArgumentParser(
    formatter_class=argparse.ArgumentDefaultsHelpFormatter)

  parser.add_argument("--image_path",
                      help="path for image to run inference",
                      default="~/demo/data/mscoco_fns/val2014/COCO_val2014_000000301397.jpg")

  args = parser.parse_args()

  args.image_path = os.path.expanduser(args.image_path)

  # Read the image
  image = skimage.io.imread(args.image_path, plugin='imageio')
  image = rescale(image, 2.0, anti_aliasing=False)
  image = img_as_ubyte(image)

  data = json.dumps({"signature_name": "predict", "instances": image.tolist()})
  headers = {"content-type": "application/json"}

  response = requests.post(SERVER_URL, data=data, headers=headers)
  response.raise_for_status()
  predictions = response.json()["predictions"]

  display_ori(image, predictions[0]) 
开发者ID:lambdal,项目名称:lambda-deep-learning-demo,代码行数:27,代码来源:object_detection_client.py

示例3: bsds500_test

# 需要导入模块: import skimage [as 别名]
# 或者: from skimage import img_as_ubyte [as 别名]
def bsds500_test(model, input_root, output_root):
    from skimage import img_as_float, img_as_ubyte
    from skimage.io import imread, imsave

    if not os.path.exists(output_root):
        os.makedirs(output_root)

    image_dir = os.path.join(input_root, "BSDS500", "data", "images", "test")
    file_names = filter(lambda name: name[-3:] == "jpg", os.listdir(image_dir))
    n_image = len(file_names)

    for i, file_name in enumerate(file_names):
        img = img_as_float(imread(os.path.join(image_dir, file_name)))

        edge = img_as_ubyte(model.predict(img))

        imsave(os.path.join(output_root, file_name[:-3] + "png"), edge)

        sys.stdout.write("Processing Image %d/%d\r" % (i + 1, n_image))
        sys.stdout.flush()
    print 
开发者ID:ArtanisCV,项目名称:StructuredForests,代码行数:23,代码来源:StructuredForests.py

示例4: _apply_

# 需要导入模块: import skimage [as 别名]
# 或者: from skimage import img_as_ubyte [as 别名]
def _apply_(self, *image):
        res = ()
        n_img = 0
        for img in image:
            if n_img == 0:
                #pdb.set_trace()
                ### transform image into HSV
                img = img_as_ubyte(color.rgb2hsv(img))
                ### perturbe each channel H, E, Dab
                for i in range(3):
                    k_i = self.params['k'][i] 
                    b_i = self.params['b'][i] 
                    img[:,:,i] = GreyValuePerturbation(img[:, :, i], k_i, b_i, MIN=0., MAX=255)
                    #plt.imshow(img[:,:,i], "gray")
                    #plt.show()
                sub_res = img_as_ubyte(color.hsv2rgb(img))
            else:
                sub_res = img

            res += (sub_res,)
            n_img += 1
        return res 
开发者ID:PeterJackNaylor,项目名称:DRFNS,代码行数:24,代码来源:ImageTransform.py

示例5: find_tissue_cnts

# 需要导入模块: import skimage [as 别名]
# 或者: from skimage import img_as_ubyte [as 别名]
def find_tissue_cnts(bw_img):
    """ Fint contours of tissues
    Parameters
    ----------
    bw_img : np.array
        2D binary image.
    Returns
    -------
    cnts: list
        List of all contours coordinates of tissues.
    """

    cnts, _ = cv2.findContours(img_as_ubyte(bw_img), mode=cv2.RETR_EXTERNAL,
                               method=cv2.CHAIN_APPROX_NONE)

    return cnts 
开发者ID:PingjunChen,项目名称:tissueloc,代码行数:18,代码来源:locate_tissue.py

示例6: count

# 需要导入模块: import skimage [as 别名]
# 或者: from skimage import img_as_ubyte [as 别名]
def count(filename, model):
    '''
    Returns an estimate of the number of grains in a given wheat image.

    Args:
        filename: Name of image file containing grains to be counted.

        model: regression model for estimating count
    Returns:
        estimation of the number of grains in image.
    '''
    img = misc.imread(filename);
    img_gray = img_as_ubyte(rgb2gray(img));

    glcm = greycomatrix(img_gray, [5], [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])

    count = model.predict(feature)
    return count 
开发者ID:oduwa,项目名称:Pic-Numero,代码行数:25,代码来源:glcm.py

示例7: print_prog

# 需要导入模块: import skimage [as 别名]
# 或者: from skimage import img_as_ubyte [as 别名]
def print_prog(self, x):
        """
        Save and print progress every self.print_rate iterations.
        """
        if (self.iter % self.print_rate) == 0:
            debug_print("gdesc iteration {}".format(str(self.iter)))
            new_img = self.transformer.deprocess(
                'data',
                x.reshape(self.net.blobs['data'].data.shape)
            )
            imsave(
                '{}/iter-{}.jpg'.format(self.dirname, self.iter),
                skimage.img_as_ubyte(new_img)
            )
            imsave(
                '{}/final.jpg'.format(self.dirname, self.iter),
                skimage.img_as_ubyte(new_img)
            )
        self.iter += 1 
开发者ID:jayelm,项目名称:neural-art,代码行数:21,代码来源:art.py

示例8: finalProcessingSpur

# 需要导入模块: import skimage [as 别名]
# 或者: from skimage import img_as_ubyte [as 别名]
def finalProcessingSpur(s, params):
    logging.info(f"{s['filename']} - \tfinalProcessingSpur")
    disk_radius = int(params.get("disk_radius", "25"))
    selem = disk(disk_radius)
    mask = s["img_mask_use"]
    mask_opened = binary_opening(mask, selem)
    mask_spur = ~mask_opened & mask

    io.imsave(s["outdir"] + os.sep + s["filename"] + "_spur.png", img_as_ubyte(mask_spur))

    prev_mask = s["img_mask_use"]
    s["img_mask_use"] = mask_opened

    s.addToPrintList("spur_pixels",
                     printMaskHelper(params.get("mask_statistics", s["mask_statistics"]), prev_mask, s["img_mask_use"]))

    if len(s["img_mask_use"].nonzero()[0]) == 0:  # add warning in case the final tissue is empty
        logging.warning(
            f"{s['filename']} - After BasicModule.finalProcessingSpur NO tissue remains detectable! Downstream modules likely to be incorrect/fail")
        s["warnings"].append(
            f"After BasicModule.finalProcessingSpur NO tissue remains detectable! Downstream modules likely to be incorrect/fail") 
开发者ID:choosehappy,项目名称:HistoQC,代码行数:23,代码来源:BasicModule.py

示例9: finalProcessingArea

# 需要导入模块: import skimage [as 别名]
# 或者: from skimage import img_as_ubyte [as 别名]
def finalProcessingArea(s, params):
    logging.info(f"{s['filename']} - \tfinalProcessingArea")
    area_thresh = int(params.get("area_threshold", "1000"))
    mask = s["img_mask_use"]

    mask_opened = remove_small_objects(mask, min_size=area_thresh)
    mask_removed_area = ~mask_opened & mask

    io.imsave(s["outdir"] + os.sep + s["filename"] + "_areathresh.png", img_as_ubyte(mask_removed_area))

    prev_mask = s["img_mask_use"]
    s["img_mask_use"] = mask_opened > 0

    s.addToPrintList("areaThresh",
                     printMaskHelper(params.get("mask_statistics", s["mask_statistics"]), prev_mask, s["img_mask_use"]))

    if len(s["img_mask_use"].nonzero()[0]) == 0:  # add warning in case the final tissue is empty
        logging.warning(
            f"{s['filename']} - After BasicModule.finalProcessingArea NO tissue remains detectable! Downstream modules likely to be incorrect/fail")
        s["warnings"].append(
            f"After BasicModule.finalProcessingArea NO tissue remains detectable! Downstream modules likely to be incorrect/fail") 
开发者ID:choosehappy,项目名称:HistoQC,代码行数:23,代码来源:BasicModule.py

示例10: removeSmallObjects

# 需要导入模块: import skimage [as 别名]
# 或者: from skimage import img_as_ubyte [as 别名]
def removeSmallObjects(s, params):
    logging.info(f"{s['filename']} - \tremoveSmallObjects")
    min_size = int(params.get("min_size", 64))
    img_reduced = morphology.remove_small_objects(s["img_mask_use"], min_size=min_size)
    img_small = np.invert(img_reduced) & s["img_mask_use"]

    io.imsave(s["outdir"] + os.sep + s["filename"] + "_small_remove.png", img_as_ubyte(img_small))
    s["img_mask_small_filled"] = (img_small * 255) > 0

    prev_mask = s["img_mask_use"]
    s["img_mask_use"] = img_reduced

    s.addToPrintList("percent_small_tissue_removed",
                     printMaskHelper(params.get("mask_statistics", s["mask_statistics"]), prev_mask, s["img_mask_use"]))


    if len(s["img_mask_use"].nonzero()[0]) == 0:  # add warning in case the final tissue is empty
        logging.warning(f"{s['filename']} - After MorphologyModule.removeSmallObjects: NO tissue "
                        f"remains detectable! Downstream modules likely to be incorrect/fail")
        s["warnings"].append(f"After MorphologyModule.removeSmallObjects: NO tissue remains "
                             f"detectable! Downstream modules likely to be incorrect/fail")

    return 
开发者ID:choosehappy,项目名称:HistoQC,代码行数:25,代码来源:MorphologyModule.py

示例11: fillSmallHoles

# 需要导入模块: import skimage [as 别名]
# 或者: from skimage import img_as_ubyte [as 别名]
def fillSmallHoles(s, params):
    logging.info(f"{s['filename']} - \tfillSmallHoles")
    min_size = int(params.get("min_size", 64))
    img_reduced = morphology.remove_small_holes(s["img_mask_use"], min_size=min_size)
    img_small = img_reduced & np.invert(s["img_mask_use"])

    io.imsave(s["outdir"] + os.sep + s["filename"] + "_small_fill.png", img_as_ubyte(img_small))
    s["img_mask_small_removed"] = (img_small * 255) > 0

    prev_mask = s["img_mask_use"]
    s["img_mask_use"] = img_reduced

    s.addToPrintList("percent_small_tissue_filled",
                     printMaskHelper(params.get("mask_statistics", s["mask_statistics"]), prev_mask, s["img_mask_use"]))

    if len(s["img_mask_use"].nonzero()[0]) == 0:  # add warning in case the final tissue is empty
        logging.warning(f"{s['filename']} - After MorphologyModule.fillSmallHoles: NO tissue "
                        f"remains detectable! Downstream modules likely to be incorrect/fail")
        s["warnings"].append(f"After MorphologyModule.fillSmallHoles: NO tissue remains "
                             f"detectable! Downstream modules likely to be incorrect/fail")
    return 
开发者ID:choosehappy,项目名称:HistoQC,代码行数:23,代码来源:MorphologyModule.py

示例12: merge_masks

# 需要导入模块: import skimage [as 别名]
# 或者: from skimage import img_as_ubyte [as 别名]
def merge_masks(masks_folder):
    masks = list()
    for mask_img_filename in os.listdir(masks_folder):
        mask_img = io.imread(os.path.join(masks_folder, mask_img_filename))
        masks.append(mask_img)

    merged_mask = np.sum(masks, axis=0)
    merged_mask[merged_mask > 0] = 1

    return img_as_ubyte(merged_mask) 
开发者ID:cosmic-cortex,项目名称:pytorch-UNet,代码行数:12,代码来源:kaggle_dsb18_preprocessing.py

示例13: encode_array_to_base64

# 需要导入模块: import skimage [as 别名]
# 或者: from skimage import img_as_ubyte [as 别名]
def encode_array_to_base64(image_array):
    with BytesIO() as output_bytes:
        PIL_image = Image.fromarray(skimage.img_as_ubyte(image_array))
        PIL_image.save(output_bytes, 'PNG')
        bytes_data = output_bytes.getvalue()
    base64_str = str(base64.b64encode(bytes_data), 'utf-8')
    return "data:image/png;base64," + base64_str 
开发者ID:gradio-app,项目名称:gradio-UI,代码行数:9,代码来源:preprocessing_utils.py

示例14: swirl_image

# 需要导入模块: import skimage [as 别名]
# 或者: from skimage import img_as_ubyte [as 别名]
def swirl_image(image):
	image = np.array(image)
	w, h = image.shape[:2]
	sw = swirl(image, rotation=0, strength=10, radius=max(w,h))
	with warnings.catch_warnings():
		warnings.simplefilter('ignore')
		sw = img_as_ubyte(sw)
	
	pil_img = Image.fromarray(sw)

	return pil_img 
开发者ID:SubhrajitPrusty,项目名称:wallgen,代码行数:13,代码来源:gradient.py

示例15: save_image_collections

# 需要导入模块: import skimage [as 别名]
# 或者: from skimage import img_as_ubyte [as 别名]
def save_image_collections(x, filename, shape=(10, 10), scale_each=False,
                           transpose=False):
    """
    :param shape: tuple
        The shape of final big images.
    :param x: numpy array
        Input image collections. (number_of_images, rows, columns, channels) or
        (number_of_images, channels, rows, columns)
    :param scale_each: bool
        If true, rescale intensity for each image.
    :param transpose: bool
        If true, transpose x to (number_of_images, rows, columns, channels),
        i.e., put channels behind.
    :return: `uint8` numpy array
        The output image.
    """
    from skimage import io, img_as_ubyte
    from skimage.exposure import rescale_intensity
    makedirs(filename)
    n = x.shape[0]
    if transpose:
        x = x.transpose(0, 2, 3, 1)
    if scale_each is True:
        for i in range(n):
            x[i] = rescale_intensity(x[i], out_range=(0, 1))
    n_channels = x.shape[3]
    x = img_as_ubyte(x)
    r, c = shape
    if r * c < n:
        print('Shape too small to contain all images')
    h, w = x.shape[1:3]
    ret = np.zeros((h * r, w * c, n_channels), dtype='uint8')
    for i in range(r):
        for j in range(c):
            if i * c + j < n:
                ret[i * h:(i + 1) * h, j * w:(j + 1) * w, :] = x[i * c + j]
    ret = ret.squeeze()
    io.imsave(filename, ret) 
开发者ID:thu-ml,项目名称:zhusuan,代码行数:40,代码来源:utils.py


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