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


Python imageio.imsave方法代码示例

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


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

示例1: imsave

# 需要导入模块: import imageio [as 别名]
# 或者: from imageio import imsave [as 别名]
def imsave(filename: str, data: np.ndarray):
    """Custom implementation of imsave to avoid skimage dependency.

    Parameters
    ----------
    filename : string
        The path to write the file to.
    data : np.ndarray
        The image data.
    """
    ext = os.path.splitext(filename)[1]
    if ext in [".tif", ".tiff"]:
        import tifffile

        tifffile.imsave(filename, data)
    else:
        import imageio

        imageio.imsave(filename, data) 
开发者ID:napari,项目名称:napari,代码行数:21,代码来源:io.py

示例2: color2annotation

# 需要导入模块: import imageio [as 别名]
# 或者: from imageio import imsave [as 别名]
def color2annotation(input_path, output_path):

    # image = scipy.misc.imread(input_path)
    # imread is deprecated in SciPy 1.0.0, and will be removed in 1.2.0. Use imageio.imread instead.
    image = imageio.imread(input_path)
    image = (image >= 128).astype(np.uint8)
    image = 4 * image[:, :, 0] + 2 * image[:, :, 1] + image[:, :, 2]
    cat_image = np.zeros((2448,2448), dtype=np.uint8)
    cat_image[image == 3] = 0  # (Cyan: 011) Urban land
    cat_image[image == 6] = 1  # (Yellow: 110) Agriculture land
    cat_image[image == 5] = 2  # (Purple: 101) Rangeland
    cat_image[image == 2] = 3  # (Green: 010) Forest land
    cat_image[image == 1] = 4  # (Blue: 001) Water
    cat_image[image == 7] = 5  # (White: 111) Barren land
    cat_image[image == 0] = 6  # (Black: 000) Unknown


    # scipy.misc.imsave(output_path, cat_image)
    imageio.imsave(output_path, cat_image)
    pass 
开发者ID:GeneralLi95,项目名称:deepglobe_land_cover_classification_with_deeplabv3plus,代码行数:22,代码来源:rgb2label.py

示例3: check_movements

# 需要导入模块: import imageio [as 别名]
# 或者: from imageio import imsave [as 别名]
def check_movements(ims, bef_ims, aft_ims, processed_roidb, delta_bef_roi, delta_aft_roi):
    save_name = '/home/wangshiyao/Documents/testdata/'+processed_roidb[0]['image'].split('/')[-1]
    print 'saving images to '+save_name
    boxes = processed_roidb[0]['boxes']
    ims.squeeze().transpose(1, 2, 0).astype(np.int8)
    bef_ims.squeeze().transpose(1, 2, 0).astype(np.int8)
    aft_ims.squeeze().transpose(1, 2, 0).astype(np.int8)
    delta_bef_roi = np.array(delta_bef_roi).transpose(1, 0, 2)
    delta_aft_roi = np.array(delta_aft_roi).transpose(1, 0, 2)
    for i in range(boxes.shape[0]):
        cv2.rectangle(ims, (int(boxes[i][0]), int(boxes[i][1])),(int(boxes[i][2]), int(boxes[i][3])),(55, 255, 155),5)
        bef_box = bbox_pred(boxes[i].reshape(1, -1), delta_bef_roi[i])
        cv2.rectangle(bef_ims, (int(bef_box[0][0]), int(bef_box[0][1])),(int(bef_box[0][2]), int(bef_box[0][3])),(55, 255, 155),5)
        aft_box = bbox_pred(boxes[i].reshape(1, -1), delta_aft_roi[i])
        cv2.rectangle(aft_ims, (int(aft_box[0][0]), int(aft_box[0][1])),(int(aft_box[0][2]), int(aft_box[0][3])),(55, 255, 155),5)

    imageio.imsave(save_name, ims)
    imageio.imsave(save_name.split('.')[-2]+'_bef'+'.JPEG', bef_ims)
    imageio.imsave(save_name.split('.')[-2]+'_aft'+'.JPEG', aft_ims) 
开发者ID:wangshy31,项目名称:MANet_for_Video_Object_Detection,代码行数:21,代码来源:image.py

示例4: main

# 需要导入模块: import imageio [as 别名]
# 或者: from imageio import imsave [as 别名]
def main(filename, width, invert, gamma, indent, chars1, chars2, title, output):
    # Aspect ratio is determined by the input image.
    # Width is determined here.
    img = load_image(filename, width, invert, gamma)
    # imageio.imsave("test.jpg", img)

    # Analyze the image
    hog_fd = process(img)

    if title:
        # title is a string
        # center it, and make bytes
        title = " " * int(indent + (width - len(title))/2) + title
        title = title.encode("utf-8")

    # Map to ASCII
    if not output:
        output = filename + ".txt"
    render(hog_fd, output, chars1, chars2, indent, title) 
开发者ID:hughpyle,项目名称:ASR33,代码行数:21,代码来源:image2.py

示例5: example_pointnav_draw_target_birdseye_view

# 需要导入模块: import imageio [as 别名]
# 或者: from imageio import imsave [as 别名]
def example_pointnav_draw_target_birdseye_view():
    goal_radius = 0.5
    goal = NavigationGoal(position=[10, 0.25, 10], radius=goal_radius)
    agent_position = np.array([0, 0.25, 0])
    agent_rotation = -np.pi / 4

    dummy_episode = NavigationEpisode(
        goals=[goal],
        episode_id="dummy_id",
        scene_id="dummy_scene",
        start_position=agent_position,
        start_rotation=agent_rotation,
    )
    target_image = maps.pointnav_draw_target_birdseye_view(
        agent_position,
        agent_rotation,
        np.asarray(dummy_episode.goals[0].position),
        goal_radius=dummy_episode.goals[0].radius,
        agent_radius_px=25,
    )

    imageio.imsave(
        os.path.join(IMAGE_DIR, "pointnav_target_image.png"), target_image
    ) 
开发者ID:facebookresearch,项目名称:habitat-api,代码行数:26,代码来源:visualization_examples.py

示例6: save_and_resize

# 需要导入模块: import imageio [as 别名]
# 或者: from imageio import imsave [as 别名]
def save_and_resize(img: np.array,
                    filename: str,
                    size=None,
                    nearest: bool=False) -> None:
    """
    Resizes the image if necessary and saves it. The resizing will keep the image ratio

    :param img: the image to resize and save (numpy array)
    :param filename: filename of the saved image
    :param size: size of the image after resizing (in pixels). The ratio of the original image will be kept
    :param nearest: whether to use nearest interpolation method (default to False)
    :return:
    """
    if size is not None:
        h, w = img.shape[:2]
        ratio = float(np.sqrt(size/(h*w)))
        resized = cv2.resize(img, (int(w*ratio), int(h*ratio)),
                             interpolation=cv2.INTER_NEAREST if nearest else cv2.INTER_LINEAR)
        imsave(filename, resized)
    else:
        imsave(filename, img) 
开发者ID:dhlab-epfl,项目名称:dhSegment,代码行数:23,代码来源:utils.py

示例7: visualize_clusters_on_disk

# 需要导入模块: import imageio [as 别名]
# 或者: from imageio import imsave [as 别名]
def visualize_clusters_on_disk(img_df):
    CLUSTER_FOLDER = 'clusters30_agg_avg'

    os.mkdir((ROOT_DIR / 'clustering' / CLUSTER_FOLDER).as_posix())

    for i in range(-1, NUM_CLUSTERS + 1):
        os.mkdir((ROOT_DIR / 'clustering' / CLUSTER_FOLDER / str(i)).as_posix())

    img_df.apply(lambda x:
                 imageio.imsave((ROOT_DIR / 'clustering' / CLUSTER_FOLDER / x['cluster-id'] /
                                 (x['ImageId'])).as_posix(), x['images']), axis=1)

    counts = img_df.groupby(['cluster-id']).size().sort_values(ascending=False)
    print(counts)

    C = list(counts.items())
    C_Sorted = sorted(C, key=lambda x: x[1]) 
开发者ID:gangadhar-p,项目名称:NucleiDetectron,代码行数:19,代码来源:cluster_images.py

示例8: call_model

# 需要导入模块: import imageio [as 别名]
# 或者: from imageio import imsave [as 别名]
def call_model(image, api_host='', model_id=''):
    tmp_filename = str(uuid.uuid4()) + '.png'
    imageio.imsave(tmp_filename, image)

    path = '/models/images/classification/classify_one.json'
    files = {'image_file': open(tmp_filename, 'rb')}

    try:
        r = post(api_host + path, files=files, params={'job_id': model_id})
    finally:
        os.remove(tmp_filename)
        time.sleep(2)  # wait 2 seconds.

    result = r.json()
    if result.get('error'):
        raise Exception(result.get('error').get('description'))

    for res_element in result['predictions']:
        if 'LIKE' in res_element[0]:
            print(result)
            return res_element[1]
    return 0.0 
开发者ID:philipperemy,项目名称:Deep-Learning-Tinder,代码行数:24,代码来源:request_model.py

示例9: computeAndCacheBG

# 需要导入模块: import imageio [as 别名]
# 或者: from imageio import imsave [as 别名]
def computeAndCacheBG(self, seqi, cami):
        bg_file_name = self.getBackgroundName(seqi, cami)
        bg_path = '/'.join(bg_file_name.split('/')[:-1])

        num_samples = 50
        import os
        names = [os.path.join(bg_path, file) for file in os.listdir(bg_path)]
        names_subsampled = names[0::len(names)//num_samples]
        image_batch = [np.array(imageio.imread(name), dtype='float32') for name in names_subsampled]
        image_batch = np.array(image_batch)
        print("Computing median of {} images".format(len(image_batch)))
        image_median = np.median(image_batch, axis=0)
        imageio.imsave(bg_file_name, image_median)
        print("Saved background image to {}".format(bg_file_name))

# training: 87395
# validation:
# testing: 28400 
开发者ID:hrhodin,项目名称:NeuralSceneDecomposition,代码行数:20,代码来源:collected_dataset.py

示例10: save_img

# 需要导入模块: import imageio [as 别名]
# 或者: from imageio import imsave [as 别名]
def save_img(img_name, img_out, val_dirs):
    assert img_name.endswith('.png')
    assert img_out.ndim == 4 and img_out.shape[1] == 3, 'Expected NCHW, got {}'.format(img_out)

    img_dir = path.join(val_dirs.out_dir, 'imgs')
    os.makedirs(img_dir, exist_ok=True)
    img_out = np.transpose(img_out[0, :, :, :], (1, 2, 0))  # Make HWC
    img_out_p = path.join(img_dir, img_name)
    print('Saving {}...'.format(img_out_p))
    imageio.imsave(img_out_p, img_out) 
开发者ID:fab-jul,项目名称:imgcomp-cvpr,代码行数:12,代码来源:val.py

示例11: visualizer

# 需要导入模块: import imageio [as 别名]
# 或者: from imageio import imsave [as 别名]
def visualizer(preds):
    # rotation, base, elbow, wrist, pitch, yaw, roll ,x, y, z, = preds
    #################################################
    #for visualization
    #################################################
    # #rotation = rotation + 90
    # #base = base - 90
    # #elbow = elbow - base
    # #wrist = wrist - elbow
    # gripper = 0
    # res = client.request('vset /arm {rotation} {base} {elbow} {wrist} {gripper}'.format(**locals()))
    # #print(res)

    # res = client.request('vset /camera/1/location {x} {y} {z}'.format(**locals()))
    # #print(res)

    # pitch = -pitch
    # yaw = yaw-180
    # roll = -roll
    # res = client.request('vset /camera/1/rotation {pitch} {yaw} {roll}'.format(**locals()))
    # #print(res)

    # print('{rotation} {base} {elbow} {wrist} {gripper} {x} {y} {z} {pitch} {yaw} {roll}'.format(**locals()))
    set_camrea(preds)

    client.request('vset /data_capture/capture_frame')

    '''

    i = 1
    data = client.request('vget /camera/{i}/lit png'.format(**locals()))
    im = read_png(data)
    io.imsave('cam_%d.png' % i, im)
    print('image saved')
    return im
    ''' 
开发者ID:zuoym15,项目名称:craves.ai,代码行数:38,代码来源:arm_controller.py

示例12: main

# 需要导入模块: import imageio [as 别名]
# 或者: from imageio import imsave [as 别名]
def main(width, height, output, star):
    if not height:
        height = int(width * 3 / 4)
    w = width * 3
    h = height * 4

    img = np.zeros([h, w], dtype=np.uint8)

    perlin(img, h, w)

    if star:
        # Overlay with a N-pointed star
        draw_star(img, h, w, points=int(star))

    imageio.imsave(output, img) 
开发者ID:hughpyle,项目名称:ASR33,代码行数:17,代码来源:perlin.py

示例13: load_image

# 需要导入模块: import imageio [as 别名]
# 或者: from imageio import imsave [as 别名]
def load_image(filename):
    if filename in loaded_files:
        return loaded_files[filename]
    img = imageio.imread(filename, as_gray=True).astype(np.float)

    # Warp it to be reasonably squared
    tf = transform.AffineTransform(rotation=ROTATION, shear=SHEAR, translation=TRANSLATION)
    img = transform.warp(img, inverse_map=tf)

    # Normalize the whole image
    # img *= 1.0/(img.max() - img.min())
    img = (img - np.min(img))/np.ptp(img)

    # Normalize on a sigmoid curve to better separate ink from paper
    k = 10
    img = np.sqrt(1 / (1 + np.exp(k * (img - 0.5))))

    # imageio.imsave("chars_overstrike_rot.png", img)
    loaded_files[filename] = img
    return img


# Pull out the image of a character-pair, c1 overstruck with c2.
# The character at (x, y) should be the same as the character at (y, x) but due to printing may be slightly
# different.  We just analyze them all anyway, and it'll sort out in the final mapping.
# (Could double the performance by folding in half, but we don't care really) 
开发者ID:hughpyle,项目名称:ASR33,代码行数:28,代码来源:prep_overstrike.py

示例14: main

# 需要导入模块: import imageio [as 别名]
# 或者: from imageio import imsave [as 别名]
def main(filename, width, invert, gamma, indent, layers):
    # Aspect ratio is determined by the input image.
    # Width is determined here.
    img = load_image(filename, width, invert, gamma)
    imageio.imsave("test.jpg", img)

    # Analyze the image
    hog_fd = process(img)

    # Map to ASCII
    render(hog_fd, layers, filename + ".txt", indent) 
开发者ID:hughpyle,项目名称:ASR33,代码行数:13,代码来源:image1.py

示例15: main

# 需要导入模块: import imageio [as 别名]
# 或者: from imageio import imsave [as 别名]
def main():
    args = get_args()
    output_path = args.output
    img_size = args.img_size

    mypath = '../data/CACD2000'
    isPlot = False
    onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]
#    landmark_list = []
#    for i in tqdm(range(len(onlyfiles))):
#        landmark_list.append(get_landmarks(onlyfiles[i], args))

    landmark_ref = np.matrix(np.load('../data/CACD_mean_face.npy', allow_pickle=True))
    
    # Points used to line up the images.
    ALIGN_POINTS = list(range(16))

    for i in tqdm(range(len(onlyfiles))):

        img_name = onlyfiles[i]        
        input_img = cv2.imread(mypath+'/'+img_name)
        input_img = cv2.cvtColor(input_img, cv2.COLOR_BGR2RGB)
        img_h, img_w, _ = np.shape(input_img)

        landmark = get_landmarks(img_name, args)[0]
        M = transformation_from_points(landmark_ref[ALIGN_POINTS], 
                                       landmark[ALIGN_POINTS])
        input_img = warp_im(input_img, M, (256, 256, 3))
        io.imsave(args.output +'/'+ img_name, input_img) 
开发者ID:Nicholasli1995,项目名称:VisualizingNDF,代码行数:31,代码来源:cacd_process.py


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