當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。