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


Python misc.imsave函数代码示例

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


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

示例1: _generate_images_for_AMT

 def _generate_images_for_AMT(self, pred_ann_ids, 
                              coco_image_dir=None, local_image_dir=None):
   """Private function to generated images to upload to AMT."""
   assert coco_image_dir and local_image_dir
   assert os.path.isdir(coco_image_dir)
   if not os.path.isdir(local_image_dir):
     print 'Input local image directory does not exist, create it'
     os.makedirs(local_image_dir)
   
   print 'Start to generate images for AMT in local hard disk'
   image_ids_saved = set()
   for (ind, pred_ann_id) in enumerate(pred_ann_ids):
     gt_data = self.refexp_dataset.loadAnns(ids = [pred_ann_id])[0]  # Need to check - change
     img = self._read_image(coco_image_dir, gt_data)
     mask = self._load_mask(gt_data)
     masked_img = cu.apply_mask_to_image(img, mask)
     masked_img_path = os.path.join(local_image_dir, ('coco_%d_ann_%d'
         '_masked.jpg' % (gt_data['image_id'], pred_ann_id)))
     misc.imsave(masked_img_path, masked_img)
     if not gt_data['image_id'] in image_ids_saved:
       image_ids_saved.add(gt_data['image_id'])
       img_path = os.path.join(local_image_dir, 'coco_%d.jpg' % gt_data['image_id'])
       misc.imsave(img_path, img)
   print ('Images generated in local hard disk, please make sure to make them '
          'publicly available online.')
开发者ID:BenJamesbabala,项目名称:Google_Refexp_toolbox,代码行数:25,代码来源:refexp_eval.py

示例2: do

    def do(self, which_callback, *args):
        from gatedpixelblocks import n_channel, batch_size, img_dim, MODE, path, dataset

        model = self.main_loop.model
        net_output = VariableFilter(roles=[OUTPUT])(model.variables)[-2]
        #print '{} output used'.format(net_output)
        Sampler = SamplerMultinomial if MODE == '256ary' else SamplerBinomial
        pred = Sampler(theano_seed=random.randint(0,1000)).apply(net_output)
        forward = ComputationGraph(pred).get_theano_function()

        # Need to replace by a scan??
        output = np.zeros((batch_size, n_channel, img_dim, img_dim), dtype=np.float32)
        x, y, c = (0,0,0)  # location
        # if input_ is not None:
        #     output[:,:c+1,:x,:y] = input_[:,:c+1,:x,:y]
        for row in range(x, img_dim):
            col_ind = y * (row == x)  # Start at column y for the first row to predict
            for col in range(col_ind, img_dim):
                for chan in range(n_channel):
                    prediction = forward(output)[0]
                    output[:,chan,row,col] = prediction[:,chan,row,col]

        output = output.reshape((4, 4, n_channel, img_dim, img_dim)).transpose((1,3,0,4,2))
        if n_channel == 1:
            output = output.reshape((4*img_dim,4*img_dim))
        else:
            output = output.reshape((4*img_dim,4*img_dim,n_channel))
        imsave(
            path+'/'+'{}_samples_epoch{}.jpg'.format(dataset, str(self.main_loop.log.status['epochs_done'])),
            output
        )
开发者ID:aalitaiga,项目名称:Generative-models,代码行数:31,代码来源:utils.py

示例3: run

 def run(self, img=misc.lena(), increase=True):
     img = misc.imread('/Users/Daniel/Desktop/p0.jpg')
     img_blurred = self.__blur(img)
     img = self.__divide(img, img_blurred)
     if False:
         img = exposure.adjust_sigmoid(img)
     misc.imsave('/Users/Daniel/Desktop/p1.jpg', img)
开发者ID:idf,项目名称:scanify,代码行数:7,代码来源:core.py

示例4: save_images

def save_images(X, save_path):
    # [0, 1] -> [0,255]
    if isinstance(X.flatten()[0], np.floating):
        X = (255.99 * X).astype('uint8')

    n_samples = X.shape[0]
    rows = int(np.sqrt(n_samples))
    while n_samples % rows != 0:
        rows -= 1

    nh, nw = rows, n_samples // rows

    if X.ndim == 2:
        X = np.reshape(X, (X.shape[0], int(np.sqrt(X.shape[1])), int(np.sqrt(X.shape[1]))))

    img = None
    if X.ndim == 4:
        # BCHW -> BHWC
        X = X.transpose(0, 2, 3, 1)
        h, w = X[0].shape[:2]
        img = np.zeros((h * nh, w * nw, 3))
    elif X.ndim == 3:
        h, w = X[0].shape[:2]
        img = np.zeros((h * nh, w * nw))

    for n, x in enumerate(X):
        j = n // nw
        i = n % nw
        img[j * h:j * h + h, i * w:i * w + w] = x

    imsave(save_path, img)
开发者ID:senior-sigan,项目名称:cppn_vae_gan,代码行数:31,代码来源:save_images.py

示例5: create_ndvi

def create_ndvi(rgb, ir, saveto=None):
    """
    Create an NDVI image

    Parameters:
        rgb - PhenoCam RGB image with same timestamp as ir
        ir - PhenoCam IR image with same timestamp as rgb
        saveto - Path to save NDVI image to (optional)

    Returns:
        ndvi - A numpy matrix representing an NDVI image.
    """
    # Extract the necessary bands
    red = rgb[:,:,0].astype(np.int16)
    ir = ir[:,:,0].astype(np.int16)

    # Create a new numpy matrix to contain the ndvi image.
    ndvi = np.zeros(red.shape)  # Should be same shape as red band

    ndvi = np.true_divide(np.subtract(ir, red), np.add(ir, red))

    if saveto:
        misc.imsave(saveto, ndvi)

    return ndvi
开发者ID:treystaff,项目名称:PhenoAnalysis,代码行数:25,代码来源:greenness.py

示例6: main

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--gpu', default=0, type=int,
                        help='if -1, use cpu only')
    parser.add_argument('-c', '--chainermodel')
    parser.add_argument('-i', '--img-files', nargs='+', required=True)
    args = parser.parse_args()

    img_files = args.img_files
    gpu = args.gpu
    chainermodel = args.chainermodel

    save_dir = 'forward_out'
    if not osp.exists(save_dir):
        os.makedirs(save_dir)

    target_names = apc2015.APC2015.target_names
    forwarding = Forwarding(gpu, target_names, chainermodel)
    for img_file in img_files:
        img, label, _ = forwarding.forward_img_file(img_file)
        out_img = forwarding.visualize_label(img, label)

        out_file = osp.join(save_dir, osp.basename(img_file))
        imsave(out_file, out_img)
        print('- out_file: {0}'.format(out_file))
开发者ID:barongeng,项目名称:fcn,代码行数:25,代码来源:forward.py

示例7: main

def main():

    input = hl.ImageParam(float_t, 3, "input")
    levels = 10

    interpolate = get_interpolate(input, levels)

    # preparing input and output memory buffers (numpy ndarrays)
    input_data = get_input_data()
    assert input_data.shape[2] == 4
    input_image = hl.Buffer(input_data)
    input.set(input_image)

    input_width, input_height = input_data.shape[:2]

    t0 = datetime.now()
    output_image = interpolate.realize(input_width, input_height, 3)
    t1 = datetime.now()
    print('Interpolated in %.5f secs' % (t1-t0).total_seconds())

    output_data = hl.buffer_to_ndarray(output_image)

    # save results
    input_path = "interpolate_input.png"
    output_path = "interpolate_result.png"
    imsave(input_path, input_data)
    imsave(output_path, output_data)
    print("\nblur realized on output image.",
          "Result saved at", output_path,
          "( input data copy at", input_path, ")")

    print("\nEnd of game. Have a nice day!")
开发者ID:darkbuck,项目名称:Halide,代码行数:32,代码来源:interpolate.py

示例8: filter_test_image

def filter_test_image(bilateral_grid, input):

    bilateral_grid.compile_jit()

    # preparing input and output memory buffers (numpy ndarrays)
    input_data = get_input_data()
    input_image = Buffer(input_data)
    input.set(input_image)

    output_data = np.empty(input_data.shape, dtype=input_data.dtype, order="F")
    output_image = Buffer(output_data)

    if False:
        print("input_image", input_image)
        print("output_image", output_image)

    # do the actual computation
    bilateral_grid.realize(output_image)

    # save results
    input_path = "bilateral_grid_input.png"
    output_path = "bilateral_grid.png"
    imsave(input_path, input_data)
    imsave(output_path, output_data)
    print("\nbilateral_grid realized on output_image.")
    print("Result saved at '", output_path,
          "' ( input data copy at '", input_path, "' ).", sep="")

    return
开发者ID:ronen,项目名称:Halide,代码行数:29,代码来源:bilateral_grid.py

示例9: markImage

def markImage(filename, minX, minY, maxX, maxY):
    img = misc.imread(PATH + filename, False)
    #print filename
    #print img.shape
    if (len(img.shape) < 3):
        img = img2rgb(img)
        
    for row in range(minY, maxY):
        img[row][minX][0] = 0
        img[row][minX][1] = 0
        img[row][minX][2] = 255
        
        img[row][maxX][0] = 0
        img[row][maxX][1] = 0
        img[row][maxX][2] = 255
        
    for col in range(minX, maxX):
        img[minY][col][0] = 0
        img[minY][col][1] = 0
        img[minY][col][2] = 255

        img[maxY][col][0] = 0
        img[maxY][col][1] = 0
        img[maxY][col][2] = 255
        
    misc.imsave(PATH+filename,img)
开发者ID:tkuboi,项目名称:eDetection_v2_1,代码行数:26,代码来源:use_maxent.py

示例10: run_example

def run_example( size = 64 ):
    """
    Run this file and result will be saved as 'rsult.jpg'
    Buttle neck: map 
    """
    modes = """
        normal
        add            substract      multiply       divide     
        dissolve       overlay        screen         pin_light
        linear_light   soft_light     vivid_light    hard_light    
        linear_dodge   color_dodge    linear_burn    color_burn
        light_only     dark_only      lighten        darken    
        lighter_color  darker_color   
        """
    top = misc.imresize( misc.imread('./imgs/top.png')[:,:,:-1], (size,size,3) )
    base = misc.imresize( misc.imread('./imgs/base.png')[:,:,:-1], (size,size,3) )
    modes = modes.split()
    num_of_mode = len( modes )
    result = np.zeros( [ size*2, size*(num_of_mode//2+2), 3 ])
    result[:size:,:size:,:] = top
    result[size:size*2:,:size:,:] = base
    for index in xrange( num_of_mode ):
        y = index // 2 + 1
        x = index % 2
        tmp= blends.blend( top, base, modes[index] )
        result[ x*size:(x+1)*size, y*size:(y+1)*size, : ] = tmp 
    # random blend
    result[-size::,-size::,:] = blends.random_blend( top, base )
    misc.imsave('result.jpg',result)
开发者ID:mertsalik,项目名称:Blends,代码行数:29,代码来源:example.py

示例11: filter_test_image

def filter_test_image(local_laplacian, input):

    local_laplacian.compile_jit()

    # preparing input and output memory buffers (numpy ndarrays)
    input_data = get_input_data()
    input_image = Image(input_data, "input_image")
    input.set(input_image)

    output_data = np.empty(input_data.shape, dtype=input_data.dtype, order="F")
    output_image = Image(output_data, "output_image")

    if False:
        print("input_image", input_image)
        print("output_image", output_image)

    # do the actual computation
    local_laplacian.realize(output_image)

    # save results
    input_path = "local_laplacian_input.png"
    output_path = "local_laplacian.png"
    imsave(input_path, input_data)
    imsave(output_path, output_data)
    print("\nlocal_laplacian realized on output_image.")
    print("Result saved at '", output_path,
          "' ( input data copy at '", input_path, "' ).", sep="")
    return
开发者ID:DoDNet,项目名称:Halide,代码行数:28,代码来源:local_laplacian.py

示例12: resize_and_save

def resize_and_save(df, img_name, true_idx, size='80x50', fraction=0.125):
    '''
    INPUT:  (1) Pandas DF
            (2) string: image name
            (3) integer: the true index in the df of the image
            (4) string: to append to filename
            (5) float: fraction to scale images by
    OUTPUT: None

    Resize and save the images in a new directory.
    Try to read the image. If it fails, download it to the raw data directory.
    Finally, read in the full size image and resize it.
    '''
    try:
        img = imread(img_name)
    except:
        cardinal_dir = img_name[-5:-4]
        cardinal_translation = {'N': 0, 'E': 90, 'S': 180, 'W': 270}
        coord = (df.ix[true_idx]['lat'], df.ix[true_idx]['lng'])
        print 'Saving new image...'
        print coord, cardinal_dir, cardinal_translation[cardinal_dir]
        save_image(coord, cardinal_translation[cardinal_dir], loc='newdata')
    finally:
        img_name_to_write = ('newdata_' + size + '/' +
                             img_name[8:-4] + size + '.png')
        if os.path.isfile(img_name_to_write) == False:
            img = imread(img_name)
            resized = imresize(img, fraction)
            print 'Writing file...'
            imsave(img_name_to_write, resized)
开发者ID:JostineHo,项目名称:streetview,代码行数:30,代码来源:organizedImageData.py

示例13: rigid_alignment

def rigid_alignment(faces,path,plotflag=False):
  """ 画像を位置合わせし、新たな画像として保存する。
      pathは、位置合わせした画像の保存先
      plotflag=Trueなら、画像を表示する """

  # 最初の画像の点を参照点とする
  refpoints = faces.values()[0]

  # 各画像を相似変換で変形する
  for face in faces:
    points = faces[face]

    R,tx,ty = compute_rigid_transform(refpoints, points)
    T = array([[R[1][1], R[1][0]], [R[0][1], R[0][0]]])

    im = array(Image.open(os.path.join(path,face)))
    im2 = zeros(im.shape, 'uint8')

    # 色チャンネルごとに変形する
    for i in range(len(im.shape)):
      im2[:,:,i] = ndimage.affine_transform(im[:,:,i],linalg.inv(T),
                                            offset=[-ty,-tx])
    if plotflag:
      imshow(im2)
      show()

    # 境界で切り抜き、位置合わせした画像を保存する
    h,w = im2.shape[:2]
    border = (w+h)/20
    imsave(os.path.join(path, 'aligned/'+face),
          im2[border:h-border,border:w-border,:])
开发者ID:Hironsan,项目名称:ComputerVision,代码行数:31,代码来源:imregistration.py

示例14: save_imgs

def save_imgs(indices, fmt, filename):
    feats = []
    true = []
    for i, idx in enumerate(indices):
        imsave(fmt.format(i), imagenes[idx])
        # labels[idx] - .5 + np.random.standard_normal()*.1,
        feats.append([1, cat_probs[idx], brightness[idx]])
        true.append(labels[idx])
    true = np.array(true)
    feats = np.array(feats)

    with open(filename,'w') as f:
        print('''<style>
            div { page-break-after: always; }
            table { border-collapse: collapse; margin: 5px; }
            td { border: 1px solid black; padding: 5px; }
        </style>''', file=f)
        for i, feat in enumerate(feats):
            print('<div>', file=f)
            print('<h1>{}</h1>'.format(i+1), file=f)
            print('<img src="{}">'.format(fmt.format(i)), file=f)
            print(
                '<table><tr>',
                ''.join('<td>{:.02f}</td>'.format(f) for f in feat),
                '</tr><tr>',
                ''.join(['<td>&nbsp;</td>'] * len(feat)),
                '</tr><tr>',
                ''.join(['<td>&nbsp;</td>'] * len(feat)),
                '</tr></table>', file=f)
            print('</div>', file=f)
开发者ID:kcarnold,项目名称:clubdl,代码行数:30,代码来源:make_gatoperro.py

示例15: dump_

 def dump_(refs, pid, cam, fnames):
     for ref in refs:
         img = deref(ref)
         if img.size == 0 or img.ndim < 2: break
         fname = '{:08d}_{:02d}_{:04d}.jpg'.format(pid, cam, len(fnames))
         imsave(osp.join(images_dir, fname), img)
         fnames.append(fname)
开发者ID:DianJin2018,项目名称:open-reid,代码行数:7,代码来源:cuhk03.py


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