예제 #1
0
def overlay_rois(im, subject, name=None, height=1024, labels=True, **kwargs):
    import shlex
    import subprocess as sp
    from matplotlib.pylab import imsave

    if name is None:
        name = 'png:-'

    key = (subject, labels)
    if key not in rois:
        print("loading %s" % subject)
        rois[key] = utils.get_roipack(subject).get_texture(height,
                                                           labels=labels)
    cmd = "composite {rois} - {name}".format(rois=rois[key].name, name=name)
    proc = sp.Popen(shlex.split(cmd), stdin=sp.PIPE, stdout=sp.PIPE)

    fp = io.StringIO()
    imsave(fp, im, **kwargs)
    fp.seek(0)
    out, err = proc.communicate(fp.read())
    if len(out) > 0:
        fp = io.StringIO()
        fp.write(out)
        fp.seek(0)
        return fp
예제 #2
0
def main():
    # 時間測定用
    ticktock = Ticktock.Ticktock()

    # 変換元の画像
    ref_image = loadSrcImage()

    # 変換元画像を分割
    # 水平方向(X方向)に分割
    num_separate = 2 #分割数
    size_x = np.shape(ref_image)[1]
    columns = split_seq(range(size_x), num_separate)
    ref_img_separated = []
    for i in range(num_separate):
        ref_img_separated.append(ref_image[:,columns[i],:]) 
    
    # モザイク画作成
    ticktock.tick()
    dest_image = []
    for i, img_in in enumerate(ref_img_separated):
        img_out = makeMosaicImage(img_in)
        dest_image.append(img_out)
#         pl.imsave(getResultPath() + "/d%d.png" % i, img_out)
    ticktock.tock()

    # 変換結果を結合
    dest_image_cat = [] 
    for i, img_out in enumerate(dest_image):
        if i==0:
            dest_image_cat = img_out
        else:
            dest_image_cat = np.hstack([dest_image_cat, img_out])
    
    # 保存
    pl.imsave(getResultPath() + "/dest.png", dest_image_cat)    
예제 #3
0
def main(globstr, beat_subdivisions, fs, quantized, wrap, save_img, debug):
    for filepath in glob.glob(globstr):
        try:
            data = pm.PrettyMIDI(filepath)
            b = data.get_beats()
            beats = interpolate_between_beats(b, beat_subdivisions)
            if quantized:
                quantize(data, beats)
            if not fs:
                cur_fs = 1. / beats[1]
                while cur_fs > wrap:
                    cur_fs = cur_fs * 0.5
            else:
                cur_fs = fs
            print("{}, {}".format(filepath, cur_fs))
            # proll = data.get_piano_roll(fs=fs, times=beats)
            proll = data.get_piano_roll(fs=cur_fs).astype(int)
            if np.isnan(proll).any():
                print("{} had NaN cells".format(filepath))
            # automatically appends .npy fo filename
            np.save(filepath, proll)
            # save image
            if save_img:
                plt.imsave(filepath + '_o.png', proll)
                plt.imsave(filepath + '_f.png', np.flipud(proll))
        except:
            print filepath, sys.exc_info()[0]
            if debug:
                traceback.print_exc()
            continue
예제 #4
0
def encode_and_save(preds_test_upsampled, test_ids):
    """
    Use run-length-encoding encode the prediction masks and save to csv file for submitting
    :param preds_test_upsampled: list, for each elements, numpy array (Width, Height)
    :param test_ids: list, for each elements, image id
    :return:
        save to csv file
    """
    # save as imgs
    for i in range(0, len(test_ids)):
        path = os.path.join(Option.results_dir, test_ids[i])
        if not os.path.exists(path):
            os.mkdir(path)
        # Image.fromarray(preds_test_upsampled[i]).save(os.path.join(path,'prediction.png'))
        plt.imsave(os.path.join(path, 'prediction.png'),
                   preds_test_upsampled[i],
                   cmap='gray')
    # save as encoding
    new_test_ids = []
    rles = []
    for n, id_ in enumerate(test_ids):
        rle = list(prob_to_rles(preds_test_upsampled[n]))
        rles.extend(rle)
        new_test_ids.extend([id_] * len(rle))

    sub = pd.DataFrame()
    sub['ImageId'] = new_test_ids
    sub['EncodedPixels'] = pd.Series(rles).apply(
        lambda x: ' '.join(str(y) for y in x))
    sub.to_csv('sub-dsbowl2018.csv', index=False)
예제 #5
0
def loadSrcImage():
    """
        変換元の画像を取得
    return : RGB配列  MxNx3 [[[R00,G00,B00], [R01,G01,B01], ... ],
                           [[R10,G10,B10], [R11,G11,B11], ... ],
                           ...
                           ]
    """
    
#     [pardir, cur] =  os.path.split(os.path.dirname(__file__))
#     [pardir, cur] =  os.path.split(os.path.dirname(sys.argv[0]))
#     prjpath = pardir + "\\"
    prjpath = "D:\\root\\programing\\Python\\MosaicImage\\" #絶対パスしていでないとインタラクティブモードで失敗する
    dirpath = "data/cifar-10-python.tar/cifar-10-batches-py/"
    file = "data_batch_1"
    fullpath = prjpath + dirpath + file
    dict = unpickle(fullpath)
    
    # 参照画像を取得
    ref_ind = 2
    ref_image = getRGBTable(dict, ref_ind)
    fname = ("ref%05d" % ref_ind) + ".png"
    
    # 参照画像を保存
    pl.imsave( getResultPath() + "/" + fname, ref_image)
     
    return ref_image
예제 #6
0
def make_svg(
    fname, braindata, recache=False, pixelwise=True, sampler="nearest", height=1024, thick=32, depth=0.5, **kwargs
):
    dataview = dataset.normalize(braindata)
    if not isinstance(dataview, dataset.Dataview):
        raise TypeError("Please provide a Dataview, not a Dataset")
    if dataview.movie:
        raise ValueError("Cannot flatten movie volumes")
    ## Create quickflat image array
    im, extents = make(
        dataview, recache=recache, pixelwise=pixelwise, sampler=sampler, height=height, thick=thick, depth=depth
    )
    ## Convert to PNG
    try:
        import cStringIO

        fp = cStringIO.StringIO()
    except:
        fp = io.StringIO()
    from matplotlib.pylab import imsave

    imsave(fp, im, cmap=dataview.cmap, vmin=dataview.vmin, vmax=dataview.vmax, **kwargs)
    fp.seek(0)
    pngdata = binascii.b2a_base64(fp.read())
    ## Create and save SVG file
    roipack = utils.get_roipack(dataview.subject)
    roipack.get_svg(fname, labels=True, with_ims=[pngdata])
예제 #7
0
    def add_prediction(self, prediction):
        dirname = os.path.dirname(self.fs.path(prediction.path))
        if not os.path.exists(dirname):
            os.makedirs(dirname)

        with self.fs.open(prediction.path, 'w') as fp:
            plt.imsave(fp, prediction.sci_bytes)
예제 #8
0
def save_fig(path, magnification=1, pixels=None, fig="gcf", **imsave_plotargs):
    """Take a screenshot and saves it to a file.

    :param path: The path, including extension, to save to.
    :type path: str or Pathlike

    :param magnification: Image dimensions relative to the size of the render (window), defaults to 1.
    :type magnification: int or a (width, height) tuple of ints, optional

    :param pixels: Image dimensions in pixels, defaults to None.
    :type pixels: int or a (width, height) tuple of ints, optional

    :param fig: The figure screenshot, defaults to vpl.gcf().
    :type fig: vpl.figure, vpl.QtFigure


    This just calls ``vpl.screenshot_fig`` then passes it to matplotlib's
    ``pylab.imsave`` function. See those for more information.

    The available file formats are determined by matplotlib's choice of
    backend. For JPEG, you will likely need to install PILLOW. JPEG has
    considerably better file size than PNG.

    """
    from matplotlib.pylab import imsave
    imsave(str(path), screenshot_fig(magnification, pixels, fig),
           **imsave_plotargs)
예제 #9
0
def dicom2jpg(dcm_filename, jpg_filename, new_size=None):
    ds = dicom.read_file(dcm_filename)
    jpg = ds.pixel_array

    # if new_size is not None:
    #     jpg = cv2.resize(jpg, new_size, interpolation=cv2.INTER_AREA)
    pylab.imsave(jpg_filename, jpg, cmap=cm.Greys_r)
예제 #10
0
def main(input):
    input_file = h5.File(input)
    output = os.path.join(args.output, os.path.basename(input))
    if not os.path.exists(output):
        os.mkdir(output)

    x0 = input_file['x0'][:]
    y0 = input_file['y0'][:]
    loss0 = input_file['loss0'][:]
    x1 = input_file['x1'][:]
    y1 = input_file['y1'][:]
    loss1 = input_file['loss1'][:]
    label = input_file['label'][:]
    id = input_file['id'][:]

    for i in range(x0.shape[0]):
        pic = x0[i]
        pic_name = '{}_{}_{}_{}.jpg'.format(int(id[i]), int(y0[i]),
                                            int(label[i]), loss0[i])
        pic_path = os.path.join(output, pic_name)
        plt.imsave(pic_path, pic.squeeze(), cmap='gray')

        pic = x1[i]
        pic_name = '{}_{}_{}_{}_{}applied.jpg'.format(int(id[i]), int(y1[i]),
                                                      int(label[i]), loss1[i],
                                                      str(y0[i] == y1[i]))
        pic_path = os.path.join(output, pic_name)
        plt.imsave(pic_path, pic.squeeze(), cmap='gray')
        if (i + 1) % 100 == 0:
            print('{} pics exported'.format(i + 1))
    print('Pic export of {} over.'.format(input))
예제 #11
0
def vis_eigen_explore(ref_code, eigvect_avg, eigv_avg, G, figdir="", RND=None, namestr="", transpose=True, eiglist=[1,2,4,7,16], maxdist=120, rown=5, sphere=False, ImDist=None, distrown=19, scaling=None):
    """This is small scale version of vis_eigen_frame + vis_distance_vector """
    if RND is None: RND = np.random.randint(10000)
    if eiglist is None: eiglist = list(range(len(eigv_avg)))
    if scaling is None: scaling = np.ones(len(eigv_avg))
    t0 = time()
    codes_page = []
    for idx, eigi in enumerate(eiglist):  # range(eig_rng[0]+1, eig_rng[1]+1):
        scaler = scaling[idx]
        if not sphere:
            interp_codes = LExpMap(ref_code, eigvect_avg[:, -eigi-1], rown, (-maxdist*scaler, maxdist*scaler))
        else:
            interp_codes = SExpMap(ref_code, eigvect_avg[:, -eigi-1], rown, (-maxdist*scaler, maxdist*scaler))
        codes_page.append(interp_codes)
    codes_all = np.concatenate(tuple(codes_page), axis=0)
    img_page = G.render(codes_all)
    mtg = build_montages(img_page, (256, 256), (rown, len(eiglist)), transpose=transpose)[0]
    imsave(join(figdir, "%s_%d-%d_%04d.jpg" % (namestr, eiglist[0]+1, eiglist[-1]+1, RND)), np.uint8(mtg * 255.0))
    plt.imsave(join(figdir, "%s_%d-%d_%04d.pdf" % (namestr, eiglist[0]+1, eiglist[-1]+1, RND)), mtg, )
    print("Finish printing page (%.1fs)" % (time() - t0))
    if ImDist is not None: # if distance metric available then compute this
        distmat, ticks, fig = vis_distance_curve(ref_code, eigvect_avg, eigv_avg, G, ImDist, eiglist=eiglist,
	        maxdist=maxdist, rown=rown, distrown=distrown, sphere=sphere, figdir=figdir, RND=RND, namestr=namestr, )
        return mtg, codes_all, distmat, fig
    else:
        return mtg, codes_all
예제 #12
0
def writeStackImages(result,outputBaseName='Arp147-'):
    '''
    Take a saved image stack (as returned by makeArp147Image()) and save out
    the individual images as something digestible by Photoshop.
    INPUTS:
        result: as returned by makeArp147Image(); or alternatively, a filename (string),
                in which case the result will be restored from that file.
        outputBaseName: the initial part of the file names to be saved out.
                        Format will be outputBaseName+'color-nnn.png', where color
                        is red/green/blue, and nnn is the frame number.
    '''
    
    bands = ['red','green','blue']
    pngmax = 255
    upperpercentile = 99.99
    
    if type(result) is str:
        result = np.load(result)
    
    nimages = np.shape(result['stack'][bands[0]])[0]
    for eachband in bands:
        print '-----'+eachband+'------'
        vals = np.copy(result['stack'][eachband]).flatten()
        upperval = np.percentile(vals[~np.isnan(vals)],upperpercentile)
        #upperval = np.nanmax(vals)
        print 'Upper val:', upperval
        for iimage in range(nimages):
            fn = outputBaseName+eachband+'-'+str(iimage).zfill(3)+'.png'
            im = result['stack'][eachband][iimage,:,:]
            #im[np.isnan(im)] = 0
            #im[im>upperval] = upperval
            #im = im*pngmax/upperval
            #scipy.misc.imsave(fn,im)
            mpl.imsave(fname=fn,arr=im,vmin=0,vmax=upperval,cmap=mpl.cm.gray)                 
def main(globstr, beat_subdivisions, fs, quantized, wrap, save_img, debug):
    for filepath in glob.glob(globstr):
        try:
            data = pm.PrettyMIDI(filepath)
            b = data.get_beats()
            beats = interpolate_between_beats(b, beat_subdivisions)
            if quantized:
                quantize(data, beats)
            if not fs:
                cur_fs = 1./beats[1]
                while cur_fs > wrap:
                    cur_fs = cur_fs * 0.5
            else:
                cur_fs = fs
            print("{}, {}".format(filepath, cur_fs))
            # proll = data.get_piano_roll(fs=fs, times=beats)
            proll = data.get_piano_roll(fs=cur_fs).astype(int)
            if np.isnan(proll).any():
                print("{} had NaN cells".format(filepath))
            # automatically appends .npy fo filename
            np.save(filepath, proll)
            # save image
            if save_img:
                plt.imsave(filepath+'_o.png', proll)
                plt.imsave(filepath+'_f.png', np.flipud(proll))
        except:
            print filepath, sys.exc_info()[0]
            if debug:
                traceback.print_exc()
            continue
예제 #14
0
def save_fig(path,
             magnification=1,
             pixels=None,
             trim_pad_width=None,
             off_screen=False,
             fig="gcf",
             **imsave_plotargs):
    """Take a screenshot and saves it to a file.

    :param path: The path, including extension, to save to.
    :type path: str or Pathlike

    :param magnification: Image dimensions relative to the size of the render (window), defaults to 1.
    :type magnification: int or a (width, height) tuple of ints, optional

    :param pixels: Image dimensions in pixels, defaults to None.
    :type pixels: int or a (width, height) tuple of ints, optional

    :param trim_pad_width: Padding to leave when cropping to contents, see :meth:`screenshot_fig`, defaults to None.
    :type trim_pad_width: int, float, optional

    :param off_screen: If true, attempt to take the screenshot without opening the figure's window, defaults to False.
    :type off_screen: bool, optional

    :param fig: The figure to save, defaults to :meth:`vtkplotlib.gcf`.
    :type fig: :class:`vtkplotlib.figure`, :class:`vtkplotlib.QtFigure`, optional


    This just calls :meth:`screenshot_fig` then passes it to matplotlib's
    ``pylab.imsave`` function. See those for more information.

    The available file formats are determined by matplotlib's choice of
    backend. For JPEG, you will likely need to install PILLOW. JPEG has
    considerably better file size than PNG.

    """
    array = screenshot_fig(magnification=magnification,
                           pixels=pixels,
                           fig=fig,
                           trim_pad_width=trim_pad_width,
                           off_screen=off_screen)

    try:
        from matplotlib.pylab import imsave
        imsave(str(path), array, **imsave_plotargs)
        return
    except ImportError:
        pass
    try:
        from PIL import Image
        Image.fromarray(array).save(str(path), **imsave_plotargs)
        return
    except ImportError:
        pass
    from vtkplotlib.image_io import write
    if write(array, path) is NotImplemented:
        raise ValueError("No writer for format '{}' could be found. Try "
                         "installing PIL for more formats.".format(
                             Path(path).ext))
예제 #15
0
    def plot_sample(self, fname='./data/sample.png', ratio=1.5, W=None, pad=1):

        X_stacked = stack_X(self.X, ratio, W, pad)
        fig = plt.imshow(stack_X(self.X, ratio, W, pad), cmap='Greys_r')
        plt.axis('off')
        fig.axes.get_xaxis().set_visible(False)
        fig.axes.get_yaxis().set_visible(False)
        plt.imsave(fname, X_stacked, format='png', cmap='Greys')
예제 #16
0
def summarize(results, samples, image_dir=None, prefix=''):
    results = dict((k, np.mean(v)) for k, v in results.items())
    logger.info(results)
    if image_dir is not None:
        plt.imsave(path.join(image_dir, '{}.png'.format(prefix)),
                   (samples.reshape(10, 10, 28, 28).transpose(
                       0, 2, 1, 3).reshape(10 * 28, 10 * 28)),
                   cmap='gray')
def plot_images(images, filename):
    h, w, c = images.shape[1:]
    grid_size = ceil(np.sqrt(images.shape[0]))
    images = (images.reshape(grid_size, grid_size, h, w,
                             c).transpose(0, 2, 1, 3,
                                          4).reshape(grid_size * h,
                                                     grid_size * w, c))
    plt.figure(figsize=(16, 16))
    plt.imsave(filename, images)
예제 #18
0
파일: qr_code.py 프로젝트: NeymarL/qr-code
    def draw(self, show=True, save=False, path='', figsize=5):
        """Draw QR code

        Args:
            show: whether to show the image or not, default is true
            save: whether to save the image or not, default is false,
              if turn on this option, you must pass the path too.
            path: where to save the image, default is empty string, 
              this argument is need only if save is true.
            figsize: the size of generate image

        Raises:
            KeyError: Invalid mode.
            NotImplementedError: It only implements mode 'Alphanumeric'
              with version 2 now.
            ValueError: 
                1. The data is too long that beyond its data capacity
                  corresponding to the error correction level
                2. Save is true but path is a empty string

        """
        # encode data
        generate_gf_table()
        self.encode()
        # draw function region
        self.draw_pos_detection_pattern()
        self.draw_alignment_pattern()
        self.draw_timing_pattern()
        self.draw_format_information()
        # assign function region
        for i in xrange(0, self.size):
            for j in xrange(0, self.size):
                self.qr_code_func[i, j] = self.qr_code_flag[i, j]

        # draw data
        self.draw_data()
        # mask
        mask = self.generate_mask()
        # xor
        for i in xrange(0, self.size):
            for j in xrange(0, self.size):
                self.qr_code_img[i, j] = int(
                    self.qr_code_img[i, j]) ^ int(mask[i, j])
        # generate image
        plt.figure(figsize=(figsize, figsize))
        plt.imshow(self.qr_code_img, cmap=plt.cm.gray_r,
                   interpolation='nearest')
        plt.axis('off')
        if show:
            # show
            plt.show()
        if save:
            if path == '':
                raise ValueError("Require path")
            # plt.savefig(path)
            plt.imsave(fname=path, arr=self.qr_code_img,
                       cmap=plt.cm.gray_r)
예제 #19
0
def vis_eigen_explore_row(ref_code,
                          eigvect_avg,
                          eigv_avg,
                          G,
                          figdir="",
                          RND=None,
                          namestr="",
                          indivimg=False,
                          transpose=True,
                          eiglist=[1, 2, 4, 7, 16],
                          maxdist=120,
                          rown=5,
                          sphere=False,
                          save=True):  # ImDist=None, distrown=19
    """This is small scale version of vis_eigen_frame + vis_distance_vector """
    if RND is None: RND = np.random.randint(10000)
    if eiglist is None: eiglist = list(range(len(eigv_avg)))
    t0 = time()
    codes_page = []
    mtg_col = []
    ticks = np.linspace(-maxdist, maxdist, rown)
    for idx, eigi in enumerate(eiglist):  # range(eig_rng[0]+1, eig_rng[1]+1):
        if not sphere:
            interp_codes = LExpMap(ref_code, eigvect_avg[:, -eigi - 1], rown,
                                   (-maxdist, maxdist))
        else:
            interp_codes = SExpMap(ref_code, eigvect_avg[:, -eigi - 1], rown,
                                   (-maxdist, maxdist))
        codes_page.append(interp_codes)
        img_page = G.render(interp_codes)
        mtg = build_montages(img_page, (256, 256), (rown, 1),
                             transpose=transpose)[0]
        if save:
            imsave(
                join(figdir, "%s_eig%d_%04d.jpg" % (namestr, eigi + 1, RND)),
                np.uint8(mtg * 255.0))
            plt.imsave(
                join(figdir, "%s_eig%d_%04d.pdf" % (namestr, eigi + 1, RND)),
                mtg,
            )
        mtg_col.append(mtg)
        if indivimg and save:
            for deviation, img in zip(ticks, img_page):
                imsave(
                    join(
                        figdir, "%s_eig%d_%.1e_%04d.jpg" %
                        (namestr, eigi + 1, deviation, RND)),
                    np.uint8(img * 255.0))
    codes_all = np.concatenate(tuple(codes_page), axis=0)
    print("Finish printing page (%.1fs)" % (time() - t0))
    # if ImDist is not None: # if distance metric available then compute this
    #     distmat, ticks, fig = vis_distance_curve(ref_code, eigvect_avg, eigv_avg, G, ImDist, eiglist=eiglist,
    #         maxdist=maxdist, rown=rown, distrown=distrown, sphere=sphere, figdir=figdir, RND=RND, namestr=namestr, )
    #     return mtg, codes_all, distmat, fig
    # else:
    return mtg_col, codes_all
예제 #20
0
def detector_batch_deploy(LogBlobDetector, inbreast_name_list):
    """Batch deploy blob detector

    Args:
        LogBlobDetector:
        inbreast_name_list:

    Returns:

    """
    inbreast_dict = inbreast.generate_inbreast_dict()
    for name in inbreast_name_list:
        print(name)
        # get paths
        try:
            mask_path = \
            list(glob.glob(os.path.join(inbreast_dict['basedir'], 'AllMASK_level2', '_combined', '{}*'.format(name))))[0]
            image_path = list(
                glob.glob(
                    os.path.join(inbreast_dict['basedir'], 'AllPNG',
                                 '{}*'.format(name))))[0]
            stack_path = list(
                glob.glob(
                    os.path.join(inbreast_dict['basedir'], 'stack',
                                 '{}*'.format(name))))[0]
        except:
            print('not found {}'.format(name))
            continue

        # read images
        img = plt.imread(image_path, -1)
        img_shape = img.shape
        img_mask = plt.imread(mask_path, -1)
        img_stack = plt.imread(stack_path, -1)
        img_overlay = (img_stack[:, img_stack.shape[1] // 2:])

        # get eroded binary mask
        det = LogBlobDetector(img,
                              max_sigma=25,
                              min_sigma=2,
                              num_sigma=3,
                              threshold=0.1,
                              disk_size=50)
        blobs_log = det.detect()

        canvas = img_overlay.copy()
        for y, x, r in blobs_log:
            cv2.circle(canvas, (int(x), int(y)),
                       int(r + 5),
                       color=(102, 255, 0),
                       thickness=2)
        # stack image side-by-side for comparison
        img_log = np.hstack([canvas, np.dstack([img] * 3)])
        plt.imsave(
            os.path.join(inbreast_dict['basedir'], 'log',
                         '{}_log_th0.1.png'.format(name)), img_log)
예제 #21
0
 def playVideo(self):
   self.framenum = 0;
   while True:
     (success, img) = self.getNextFrame()
     if success == False:
       break;
     savename = '/scail/group/deeplearning/driving_data/stillimgs/280N_right_%d.png'%(self.framenum)
     img = img[:,:,::-1]
     print savename
     pp.imsave(savename, img)
def plot_images(images, filename):
    # scale images to [0.0, 1.0]
    images = (images + 1) / 2
    h, w, c = images.shape[1:]
    grid_size = ceil(np.sqrt(images.shape[0]))
    images = (images.reshape(grid_size, grid_size, h, w, c)
              .transpose(0, 2, 1, 3, 4)
              .reshape(grid_size*h, grid_size*w, c))
    plt.figure(figsize=(16, 16))
    plt.imsave(filename, images)
    plt.close('all')
예제 #23
0
 def playVideo(self):
     self.framenum = 0
     while True:
         (success, img) = self.getNextFrame()
         if success == False:
             break
         savename = '/scail/group/deeplearning/driving_data/stillimgs/280N_right_%d.png' % (
             self.framenum)
         img = img[:, :, ::-1]
         print savename
         pp.imsave(savename, img)
예제 #24
0
def main():
    parser = ap.ArgumentParser()
    parser.add_argument('--directory', type=str, help='The directory of where SUNRGBD is stored.')
    parser.add_argument('--imfile', type=int, help='The number of image in NYU dataset.') 
    args = parser.parse_args()
    dataset_file = args.directory + ('SUNRGBD/kv1/NYUdata/NYU%04d/image/NYU%04d.jpg' % (args.imfile, args.imfile))
    print('Extracting the file' + dataset_file)
    im = skimage.io.imread(dataset_file)
    seg_mask = skimage.segmentation.quickshift(im)
    normalized_seg = seg_mask.astype(np.float)/np.amax(seg_mask)*255
    plt.imsave("quickshift.jpg", normalized_seg, cmap=new_map)
예제 #25
0
def main():
    model = mocap.model.AlgModel()
    data_reader = mocap.data.H36mDataReader()
    vis = mocap.vis.Visualizer()
    for iter_i in tqdm(range(100)):
        cameras = data_reader.load_cameras(iter_i)
        images = data_reader.load_images(iter_i)
        prediction = model.infer(cameras, images)
        for batch_index in range(images.shape[0]):
            fig = vis.vis_batch_2d(images, prediction.d2, cameras, prediction.d3, batch_index)
            plt.imsave('vis_%d_%d.png' % (iter_i, batch_index), fig)
    pdb.set_trace()
예제 #26
0
    def plot_sample(self, fname=None, ratio = 1.5, W = None, pad = 1):

        X_stacked = stack_X(self.X.reshape((-1, *self.shape_2d)), ratio, W, pad)
        fig = plt.imshow(X_stacked, cmap='Greys_r')
        plt.axis('off')
        fig.axes.get_xaxis().set_visible(False)
        fig.axes.get_yaxis().set_visible(False)

        if fname is None:
            logger.info('Showing plot...')
        else:
            plt.imsave(fname, X_stacked, format='png', cmap='Greys')
예제 #27
0
def shift_image(path, shift):
    rgb, depth = h5_loader(path)
    shift_depth_transform = ShiftDepth(shift=shift)
    shifted_depth = shift_depth_transform(depth)

    # Fix the wrong colormap issue
    if shift == 0:
        shifted_depth = np.pad(shifted_depth, (1, 0), 'constant')

    import matplotlib.pylab as plt
    import os
    fname = os.path.basename(path)
    plt.imsave(fname[:5] + '_shift_' + str(shift) + '.jpg', shifted_depth)
예제 #28
0
 def show_path(self, start, goal, came_from,
               img_high=None, scale=1, save=False):
     if not img_high: img_high = self.figname
     fig2 = pylab.imread(img_high)
     current = goal
     while not current == start:
         x, y = current
         x *= scale
         y *= scale
         fig2[y][x] = np.array([255, 0, 0], dtype=np.uint8)
         current = came_from[current]
     pylab.imshow(fig2)
     if save:
         pylab.imsave(arr=fig2, fname=img_high[:-4]+'_minpath.png')
예제 #29
0
    def _export_atlas(self, atlas, suffix=''):
        """ export estimated atlas

        :param ndarray atlas: np.array<height, width>
        :param str suffix:
        """
        n_img = NAME_ATLAS.format(suffix)
        export_image(self.params.get('path_exp'),
                     atlas,
                     n_img,
                     stretch_range=False)
        path_atlas_rgb = os.path.join(self.params.get('path_exp'),
                                      n_img + '_rgb.png')
        logging.debug('exporting RGB atlas: %s', path_atlas_rgb)
        plt.imsave(path_atlas_rgb, atlas, cmap=plt.cm.jet)
예제 #30
0
def infer(data_filepath='data/flowers.hdf5',
          z_dim=128,
          out_dir='gan',
          n_steps=10):

    G = load_model(out_dir)
    val_data = get_data(data_filepath, 'train')
    val_data = next(iterate_minibatches(val_data, 2))
    emb_a, emb_b = val_data[1]
    txts = val_data[2]

    # add batch dimension
    emb_a, emb_b = emb_a[None, :], emb_b[None, :]

    # sample z vector for inference
    z = np.random.uniform(-1, 1, size=(1, z_dim))

    G.trainable = False
    # predict using embeddings a and b
    fake_image_a = G.predict([z, emb_a])[0]
    fake_image_b = G.predict([z, emb_b])[0]

    # add and subtract
    emb_add = (emb_a + emb_b)
    emb_a_sub_b = (emb_a - emb_b)
    emb_b_sub_a = (emb_b - emb_a)

    # generate images
    fake_a = G.predict([z, emb_a])[0]
    fake_b = G.predict([z, emb_b])[0]
    fake_add = G.predict([z, emb_add])[0]
    fake_a_sub_b = G.predict([z, emb_a_sub_b])[0]
    fake_b_sub_a = G.predict([z, emb_b_sub_a])[0]

    fake_a = ((fake_a + 1) * 0.5)
    fake_b = ((fake_b + 1) * 0.5)
    fake_add = ((fake_add + 1) * 0.5)
    fake_a_sub_b = ((fake_a_sub_b + 1) * 0.5)
    fake_b_sub_a = ((fake_b_sub_a + 1) * 0.5)

    plt.imsave("{}/fake_text_arithmetic_a".format(out_dir), fake_a)
    plt.imsave("{}/fake_text_arithmetic_b".format(out_dir), fake_b)
    plt.imsave("{}/fake_text_arithmetic_add".format(out_dir), fake_add)
    plt.imsave("{}/fake_text_arithmetic_a_sub_b".format(out_dir), fake_a_sub_b)
    plt.imsave("{}/fake_text_arithmetic_b_sub_a".format(out_dir), fake_b_sub_a)
    print(str(txts[0]),
          str(txts[1]),
          file=open("{}/fake_text_arithmetic.txt".format(out_dir), "a"))
예제 #31
0
def save_image(image, file_name, grayscale=True):
    if len(image.shape) == 2 or grayscale == True:
        if len(image.shape) == 3:
            image = np.sum(np.abs(image), axis=2)
        vmax = np.percentile(image, 99)
        vmin = np.min(image)
        plt.imsave(fname=file_name,
                   arr=image,
                   cmap=plt.cm.gray,
                   vmin=vmin,
                   vmax=vmax,
                   dpi=100)
    else:
        image = image + 127.5
        image = image.astype('uint8')
        plt.imsave(fname=file_name, arr=image, dpi=100)
예제 #32
0
def plot(samples):
    fig = plt.figure(figsize=(4, 4))
    gs = gridspec.GridSpec(4, 4)
    gs.update(wspace=0.05, hspace=0.05)

    for i, sample in enumerate(samples):
        ax = plt.subplot(gs[i])
        plt.axis('off')
        ax.set_xticklabels([])
        ax.set_yticklabels([])
        ax.set_aspect('equal')
        # print(sample.shape)
        sample = sample.reshape(128, -1)
        # print(np.array([[[sample[i][j], sample[i][j], sample[i][j], 1.0] for j in range(sample.shape[1])] for i in range(sample.shape[0])]))
        plt.imsave('../gan_result/{}.png'.format(str(i).zfill(3)), np.array([[[sample[i][j], sample[i][j], sample[i][j], 1.0] for j in range(sample.shape[1])] for i in range(sample.shape[0])]), cmap='Greys_r')

    return fig
예제 #33
0
def imwrite(fname: str, image: np.array):
    """save any 2d numpy array (or list) to an image file

    Parameters
    ----------
    fname : str
        flie name to be saved
    image : np.array
        2d numpy array (or list) to be saved
    """
    if "pathlib" in str(type(fname)):
        fname = fname.as_posix()
    if HAS_OPENCV:
        cv2.imwrite(fname, image)
    else:
        plt.imsave(fname, image)
        
예제 #34
0
def rescale_2(name, scale):
    img_origin = Image.open('sent_photo/' + name + '.png')
    img_origin.save('sent_photo/' + name + '.png')
    img = plt.imread('sent_photo/' + name + '.png')
    size = (len(img), len(img[0]))
    splice_x = find_splice(size[0])
    splice_y = find_splice(size[1])
    new_img = np.zeros((scale, scale, 3))
    for i in range(scale):
        for j in range(scale):
            x_b, x_e = splice_x[1] * i, splice_x[0] + splice_x[1] * i
            y_b, y_e = splice_y[1] * j, splice_y[0] + splice_y[1] * j
            for channel in range(3):
                bite = img[x_b:x_e, y_b:y_e, channel]
                new_img[i, j, channel] = np.mean(bite)
    plt.imsave('rescale_photo/' + name + '_s.png', new_img, cmap='gray')
    return new_img
def save_images_for_debug(dir_img, imgs):
    """
    2x3x12x224x224 --> [BS, C, seq_len, H, W]
    """
    print("Saving images to {}".format(dir_img))
    from matplotlib import pylab as plt
    imgs = imgs.permute(0, 2, 3, 4, 1)  # [BS, seq_len, H, W, C]
    imgs = imgs.mul(255).numpy()
    if not os.path.exists(dir_img):
        os.makedirs(dir_img)
    print(imgs.shape)
    for batch_id, batch in enumerate(imgs):
        batch_dir = os.path.join(dir_img, "batch{}".format(batch_id + 1))
        if not os.path.exists(batch_dir):
            os.makedirs(batch_dir)
        for j, img in enumerate(batch):
            plt.imsave(os.path.join(batch_dir, "frame{%04d}.png" % (j + 1)),
                       img.astype("uint8"))
예제 #36
0
def infer(data_filepath='data/flowers.hdf5', z_dim=128, out_dir='gan',
          n_samples=5):

    G = load_model(out_dir)
    val_data = get_data(data_filepath, 'train')
    val_data = next(iterate_minibatches(val_data, n_samples))    
    emb, txts = val_data[1], val_data[2]

    # sample z vector for inference
    z = np.random.uniform(-1, 1, size=(n_samples, z_dim))

    G.trainable = False
    fake_images = G.predict([z, emb])
    for i in range(n_samples):
        img = ((fake_images[i] + 1)*0.5)
        plt.imsave("{}/fake_{}".format(out_dir, i), img)
        print(i, str(txts[i]).strip(),
              file=open("{}/fake_text.txt".format(out_dir), "a"))
예제 #37
0
 def show_path(self,
               start,
               goal,
               came_from,
               img_high=None,
               scale=1,
               save=False):
     if not img_high: img_high = self.figname
     fig2 = pylab.imread(img_high)
     current = goal
     while not current == start:
         x, y = current
         x *= scale
         y *= scale
         fig2[y][x] = np.array([255, 0, 0], dtype=np.uint8)
         current = came_from[current]
     pylab.imshow(fig2)
     if save:
         pylab.imsave(arr=fig2, fname=img_high[:-4] + '_minpath.png')
예제 #38
0
def run_fix(ld = 2, u = 8, Q1 = 0.05, Q2 = 0.1, img = ''):
    if not img:
        img = plt.imread('test/Sublime_text.png')
    else:
        img = plt.imread(img)

    if img.max() >= 200:
        img /= 255.0

    #plt.figure()
    #plt.imshow(img)

    #plt.figure()
    new = np.zeros(img.shape)
    for i in range(img.shape[2]):
        new[:, :, i] = fix_image(img[:, :, i], ld, u, Q1, Q2)

    #plt.imshow(new)
    filename = generate_random_file_name()
    plt.imsave('static/temp/' + filename, new)
    return 'static/temp/' + filename
예제 #39
0
파일: mask.py 프로젝트: johannah/iceview
def find_mask(base_name, base_img, img_name, img, model_robust, channel):
    # what type of interpolation
    # 0: nearest-neighbor
    # 1: bi-linear
    warp_order = 1
    output_shape, corner_min = find_output_shape(base_img, model_robust, channel)
    # This in-plane offset is the only necessary transformation for the base image
    offset = SimilarityTransform(translation= -corner_min)
    base_warped = warp(base_img[:,:,channel], offset.inverse, order=warp_order,
                      output_shape = output_shape, cval=-1)
    base_color = warp(base_img, offset.inverse, order=warp_order,
                      output_shape = output_shape, cval=-1)
    # warp image corners to new position in mosaic
    transform = (model_robust + offset).inverse

    img_warped = warp(img[:,:,channel], transform, order=warp_order,
                      output_shape=output_shape, cval=-1)
    img_color = warp(img, transform, order=warp_order,
                      output_shape=output_shape, cval=-1)
    base_mask = (base_warped != -1)
    base_warped[~base_mask] = 0

    img_mask = (img_warped != -1)
    img_warped[~img_mask] = 0
    plt.imsave("img_mask.jpg", img_mask)

    #convert to rgb
    img_alpha = np.dstack((img_color, img_mask))
    base_alpha = np.dstack((base_color, base_mask))

    td = config.tmp_dir
    tmp_base = os.path.join(td, 'tmp_' + '.'.join(base_name.split('.')[:-1]) + '.png')
    tmp_img = os.path.join(td, 'tmp_' + '.'.join(img_name.split('.')[:-1]) + '.png')
    tmp_out = os.path.join(td, 'tmp_out_' + '.'.join(base_name.split('.')[:-1]) + '.png')

    plt.imsave(tmp_base, base_alpha)
    plt.imsave(tmp_img, img_alpha)

    cmd = ['enblend', tmp_base, tmp_img, '-o', tmp_out]

    p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)
    output, err = p.communicate(b"input data that is passed to subprocess' stdin")
    rc = p.returncode
    #if you don't have enblend, you can use one of these
    #merged_img = simple_merge(base_warped, img_warped, base_mask, img_mask)
    #merged_img = minimum_cost_merge(base_warped, img_warped, base_mask, img_mask)
    #merged_edges = remove_empty_edges(merged_img)
    # remove alpha channel
    if os.path.exists(tmp_out):
        out = imread(tmp_out)
        oute = remove_empty_alpha(out)
        os.remove(tmp_base)
        os.remove(tmp_img)
        os.remove(tmp_out)
        return oute[:,:,:3]
    else:
        print("Could not find out", tmp_out, rc)
        raise Exception("failed cmd %s" %cmd)
예제 #40
0
def overlay_rois(im, subject, name=None, height=1024, labels=True, **kwargs):
    import shlex
    import subprocess as sp
    from matplotlib.pylab import imsave

    if name is None:
        name = 'png:-'

    key = (subject, labels)
    if key not in rois:
        print("loading %s"%subject)
        rois[key] = utils.get_roipack(subject).get_texture(height, labels=labels)
    cmd = "composite {rois} - {name}".format(rois=rois[key].name, name=name)
    proc = sp.Popen(shlex.split(cmd), stdin=sp.PIPE, stdout=sp.PIPE)

    fp = io.StringIO()
    imsave(fp, im, **kwargs)
    fp.seek(0)
    out, err = proc.communicate(fp.read())
    if len(out) > 0:
        fp = io.StringIO()
        fp.write(out)
        fp.seek(0)
        return fp
예제 #41
0
파일: view.py 프로젝트: gallantlab/pycortex
def make_svg(fname, braindata, with_labels=False, with_curvature=True, layers=['rois'],
             height=1024, **kwargs):
    """Save an svg file of the desired flatmap.

    This function creates an SVG file with vector graphic ROIs overlaid on a single png image.
    Ideally, this function would layer different images (curvature, data, dropout, etc), but
    that has been left to implement at a future date if anyone really wants it.

    Parameters
    ----------
    fname : string
        file name to save
    braindata : Dataview
        the data you would like to plot on a flatmap
    with_labels : bool
        Whether to display text labels on ROIs
    with_curvature : bool
        Whether to include background curvature
    layers : list
        List of layer names to show
    height : int
        Height of PNG in pixels

    """
    fp = io.BytesIO()
    from matplotlib.pylab import imsave

    ## Render PNG file & retrieve image data
    arr, extents = make_flatmap_image(braindata, height=height, **kwargs)

    if hasattr(braindata, 'cmap'):
        imsave(fp, arr, cmap=braindata.cmap, vmin=braindata.vmin, vmax=braindata.vmax)
    else:
        imsave(fp, arr)
    fp.seek(0)
    pngdata = binascii.b2a_base64(fp.read())
    image_data = [pngdata]

    if with_curvature:
        # no options. learn to love it.
        from cortex import db
        fpc = io.BytesIO()
        curv_vertices = db.get_surfinfo(braindata.subject)
        curv_arr, _ = make_flatmap_image(curv_vertices, height=height)
        mask = np.isnan(curv_arr)
        curv_arr = np.where(curv_arr > 0, 0.5, 0.25)
        curv_arr[mask] = np.nan

        imsave(fpc, curv_arr, cmap='Greys_r', vmin=0, vmax=1)
        fpc.seek(0)
        image_data = [binascii.b2a_base64(fpc.read()), pngdata]

    ## Create and save SVG file
    roipack = utils.get_roipack(braindata.subject)
    roipack.get_svg(fname, layers=layers, labels=with_labels, with_ims=image_data)
        g_loss = g_train_fn(g_X, g_C, g_M)
        generator_updates += 1

        c_epoch_losses.append(np.mean(c_losses))
        g_epoch_losses.append(g_loss)

        fig, axes = plt.subplots(1, 3, figsize=(8, 2))
        axes[0].set_title('Loss(d)')
        axes[0].plot(c_losses)
        axes[1].set_title('Mean(Loss(d))')
        axes[1].plot(c_epoch_losses)
        axes[2].set_title('Loss(g)')
        axes[2].plot(g_epoch_losses)
        fig.tight_layout()
        fig.savefig('images/{}/g_updates{}'.format(folderpath, generator_updates))
        plt.close('all')
        display.clear_output(wait=True)

    noise = lasagne.utils.floatX(np.random.normal(size=g_specs['noise_shape']))
    rand_ids = np.random.randint(0, g_specs['noise_shape'][0], 64)
    samples = g_sample_fn(c_X, noise, c_C, c_M)[rand_ids]
    plt.imsave('images/{}/epoch{}_samples.png'.format(folderpath, epoch),
               (samples.reshape(8, 8, max_len, n_features)
                       .transpose(0, 2, 1, 3)
                       .reshape(8*max_len, 8*n_features)).T,
               cmap='gray',
               origin='bottom')

    plt.close('all')
    display.clear_output(wait=True)
예제 #43
0
plt.show()

test_labels, test_data = [], []
for line in open('./faces/test.txt'):
    im = misc.imread(line.strip().split()[0])
    test_data.append(im.reshape(2500,))
    test_labels.append(line.strip().split()[1])
test_data, test_labels = np.array(test_data, dtype=float), np.array(test_labels, dtype=int)

# Part c Calculate Mean
mu = np.sum(train_data,axis=0)
mu /= train_data.shape[0]
print mu
plt.imshow(mu.reshape(50,50),cmap = cm.Greys_r)
plt.show()
plt.imsave("Mean.png",mu.reshape(50,50), cmap = cm.Greys_r)

# Part d Subtract Mean
for i in range(train_data.shape[0]):
    train_data[i] = train_data[i] - mu
plt.imshow(train_data[10, :].reshape(50,50), cmap = cm.Greys_r)
for i in range(test_data.shape[0]):
    test_data[i] = test_data[i] - mu
plt.imshow(test_data[10, :].reshape(50,50), cmap = cm.Greys_r)

# Part e SVD
U, s, V = np.linalg.svd(train_data, full_matrices=False)
for i in range(10):
    plt.imshow(V[i].reshape(50,50), cmap = cm.Greys_r)
    plt.show()
    plt.imsave(str(i)+".png",V[i].reshape(50,50), cmap = cm.Greys_r)
예제 #44
0
    # Find the chess board corners.
    Found, Corners = cv2.findChessboardCorners(Image_BW, PatternSize)

    # If found, refine the image points, add them to their lists and draw
    # the chessboard corners on the images
    if Found:
        print 'Found pattern!'
        # Find more precise corner points. The fist tuple influences the side
        # length of the search window. The second tuple is the dead region in
        # the middle of the search zone, see http://is.gd/xm6SXi
        cv2.cornerSubPix(Image_BW, Corners, (30, 30), (-1, -1), criteria)
        ImagePoints.append(Corners)
        RealWorldPoints.append(ObjectPoints)
        cv2.drawChessboardCorners(Image, PatternSize, Corners, Found)
        plt.imsave(FileName[:-4] + '_pattern.png', Image)
        print 'Saving found pattern image as %s' % FileName[:-4] + '_pattern.png'
    plt.subplot(3, 4, 11 - counter + 1)
    plt.imshow(ndimage.rotate(Image, 270), cmap='gray',
               interpolation='nearest')
    ImageTitle = os.path.basename(FileName)
    if Found:
        ImageTitle = '\n'.join(('Pattern found on', ImageTitle))
    plt.title(ImageTitle)
    plt.axis('off')

if not ImagePoints:
    print 'I was not able to find a pattern on any image, maybe try ' \
          'another "PatternSize"...'
    exit('PatternNotFound')
예제 #45
0
plt.ylim([0, 75])
plt.legend(loc='best')
plt.title('Voltage vs. Current')
for c, i in enumerate(CompareImages):
    print '%s/%s | %s kV/%s uA | Comparing %s with %s' % (
        c + 1, len(CompareImages), VoltageERI[c], CurrentERI[c],
        bold(os.path.basename(i)),
        bold(os.path.basename(ImageListERI[c])))
    ImageERI = plt.imread(ImageListERI[c])
    ImageHamamatsu = plt.imread(i)
    plt.subplot(gs[:2, 1:])
    plt.imshow(plt.imread(ImageListERI[c]))
    plt.axis('off')
    plt.subplot(gs[2:, 1:])
    plt.imshow(plt.imread(i))
    plt.axis('off')
    plt.subplots_adjust(wspace=0.02, hspace=0, left=0.03, right=1,
                        top=1, bottom=0)
    plt.draw()
    # Save figure and concatenated results
    plt.savefig(os.path.join(OutputPath, '%02d' % VoltageERI[c] + 'kV' +
                             str(CurrentERI[c]) + 'uA.png'))
    ConcatenateImage = numpy.concatenate((ImageERI, ImageHamamatsu), axis=0)
    plt.imsave(os.path.join(OutputPath, 'Concatenate_%02d' % VoltageERI[c] +
                            'kV' + str(CurrentERI[c]) + 'uA.png'),
               ConcatenateImage)

plt.ioff()
plt.show()
print 'Done with everything!'
예제 #46
0
    dirpath = "data/cifar-10-python.tar/cifar-10-batches-py/"
    file = "data_batch_1"
    fullpath = prjpath + dirpath + file
    dict = unpickle(fullpath)
    
    data = dict['data']
    labels = dict['labels'] 
    num = np.size(labels) #データ数

    ticktock = Ticktock.Ticktock()

    # 参照画像を取得
    ref_ind = 2
    ref_image = getRGBTable(dict, ref_ind)
    fname = ("ref%05d" % ref_ind) + ".png"
    pl.imsave(prjpath+"result\\py04\\" + fname, ref_image)

    ticktock.tick()

    range_xy = np.shape(ref_image)
    dest_image = np.zeros([range_xy[0]*32, range_xy[1]*32, 3], dtype='uint8') #uint8で作るのが大事
    for x in range(range_xy[0]):
        print x
        for y in range(range_xy[1]):
            ref_rgb = ref_image[x,y,:]
            # 一番色が近い画像を求める
            [minind, rss] = findNearestColorImage(dict, ref_rgb, range(100))
#             [minind, rss] = findNearestColorImage(dict, ref_rgb, range(10000))
        #     [minind, rss] = findNearestColorImage(dict, ref_rgb)
            # 一番近い画像を取得
            near_rgb = getRGBTable(dict, minind)
예제 #47
0
    # P=-ln((P-D)/(F-D)), while D and F are mean darks and mean flats
    CorrectedImage = numpy.negative(
        numpy.log(numpy.divide(numpy.subtract(ProjectionImage, AverageDark), numpy.subtract(AverageFlat, AverageDark)))
    )

    plt.clf()
    plt.subplot(231)
    plt.imshow(AverageFlat)
    plt.title("Average flat")
    plt.subplot(232)
    plt.imshow(AverageDark)
    plt.title("Average dark")
    plt.subplot(233)
    plt.imshow(ProjectionImage)
    plt.title("Raw projection\n(%s)" % os.path.basename(p))
    plt.subplot(212)
    plt.imshow(CorrectedImage)
    plt.title("Corrected image")
    plt.suptitle(
        "%s\nImage acquired at %skV and %suA\nwith a Detector "
        "exposure time of %ss" % (os.path.basename(p.split("_")[0]), Voltage, Current, ExposureTime)
    )
    plt.savefig(os.path.splitext(p)[0] + ".figure.png")
    plt.imsave(os.path.splitext(p)[0] + ".corrected.png", CorrectedImage)
    plt.draw()

print "Done"
plt.ioff()
plt.show()
def makeImageStack(fileNames='photons_*.h5', dir=os.getenv('MKID_PROC_PATH', 
                   default="/Scratch")+'/photonLists/20121211',
                   detImage=False, saveFileName='stackedImage.pkl', wvlMin=3500,
                   wvlMax=12000, doWeighted=True, medCombine=False, vPlateScale=0.2,
                   nPixRA=250,nPixDec=250,maxBadPixTimeFrac=0.2,integrationTime=-1,
                   outputdir=''):
    '''
    Create an image stack
    INPUTS:
        filenames - string, list of photon-list .h5 files. Can either
                    use wildcards (e.g. 'mydirectory/*.h5') or if string
                    starts with an @, supply a text file which contains
                    a list of file names to stack. (e.g.,
                    'mydirectory/@myfilelist.txt', where myfilelist.txt 
                    is a simple text file with one file name per line.)
        dir - to provide name of a directory in which to find the files
        detImage - if True, show the images in detector x,y coordinates instead
                    of transforming to RA/dec space.
        saveFileName - name of output pickle file for saving final resulting object.
        doWeighted - boolean, if True, do the image flatfield weighting.
        medCombine - experimental, if True, do a median combine of the image stack
                     instead of just adding them all.... Prob. should be implemented
                     properly at some point, just a fudge for now.
        vPlateScale - (arcsec/virtual pixel) - to set the plate scale of the virtual
                     pixels in the outputs image.
        nPixRA,nPixDec - size of virtual pixel grid in output image.
        maxBadPixTimeFrac - Maximum fraction of time which a pixel is allowed to be 
                     flagged as bad (e.g., hot) for before it is written off as
                     permanently bad for the duration of a given image load (i.e., a
                     given obs file).
        integrationTime - the integration time to use from each input obs file (from 
                     start of file).
    OUTPUTS:
        Returns a stacked image object, saves the same out to a pickle file, and
        (depending whether it's still set to or not) saves out the individual non-
        stacked images as it goes. 
    '''
    

    #Get the list of filenames
    if fileNames[0]=='@':
        #(Note, actually untested, but should be more or less right...)
        files=[]
        with open(fileNames[1:]) as f:
            for line in f:
                files.append(os.path.join(dir,line.strip()))
    else:
        files = glob.glob(os.path.join(dir, fileNames))

    #Initialise empty image centered on Crab Pulsar
    virtualImage = rdi.RADecImage(nPixRA=nPixRA,nPixDec=nPixDec,vPlateScale=vPlateScale,
                                  cenRA=1.4596725441339724, cenDec=0.38422539085925933)
    imageStack = []
                                  
    for eachFile in files:
        if os.path.exists(eachFile):
            print 'Loading: ',os.path.basename(eachFile)
            #fullFileName=os.path.join(dir,eachFile)
            phList = pl.PhotList(eachFile)
            baseSaveName,ext=os.path.splitext(os.path.basename(eachFile))
            
            if detImage is True:
                imSaveName=os.path.join(outputdir,baseSaveName+'det.tif')
                im = phList.getImageDet(wvlMin=wvlMin,wvlMax=wvlMax)
                utils.plotArray(im)
                mpl.imsave(fname=imSaveName,arr=im,colormap=mpl.cm.gnuplot2,origin='lower')
                if eachFile==files[0]:
                    virtualImage=im
                else:
                    virtualImage+=im
            else:
                imSaveName=os.path.join(outputdir,baseSaveName+'.tif')
                virtualImage.loadImage(phList,doStack=not medCombine,savePreStackImage=imSaveName,
                                       wvlMin=wvlMin, wvlMax=wvlMax, doWeighted=doWeighted,
                                       maxBadPixTimeFrac=maxBadPixTimeFrac, integrationTime=integrationTime)
                imageStack.append(virtualImage.image*virtualImage.expTimeWeights)       #Only makes sense if medCombine==True, otherwise will be ignored
                if medCombine==True:
                    medComImage = scipy.stats.nanmedian(np.array(imageStack), axis=0)
                    toDisplay = np.copy(medComImage)
                    toDisplay[~np.isfinite(toDisplay)] = 0
                    utils.plotArray(toDisplay,pclip=0.1,cbar=True,colormap=mpl.cm.gray)
                else:
                    virtualImage.display(pclip=0.5,colormap=mpl.cm.gray)
                    medComImage = None

            mpl.show() 


        else:
            print 'File doesn''t exist: ',eachFile
    
    #Save the results.
    #Note, if median combining, 'vim' will only contain one frame. If not, medComImage will be None.
    results = {'vim':virtualImage,'imstack':imageStack,'medim':medComImage}

    try:
        output = open(os.path(outputdir,saveFileName),'wb')
        pickle.dump(results,output,-1)
        output.close()
            
    except:
        warnings.warn('Unable to save results for some reason...')
    
    return results
예제 #49
0
    ticktock = Ticktock.Ticktock()

    # 平均値一覧を取得
    means = calMeans(dict)

    # 参照画像を取得
    ref_ind = 2
    ref_image = getRGBTable(dict, ref_ind)
    fname = ("ref%05d" % ref_ind) + ".png"
    resultpath = prjpath+"result"
    resultpath2 = resultpath + "/py04"
    if os.path.exists(resultpath) == False:
        os.mkdir(resultpath)
    if os.path.exists(resultpath2 ) == False:
        os.mkdir(resultpath2)
    pl.imsave(resultpath2 + "/" + fname, ref_image)

    ticktock.tick()

    range_xy = np.shape(ref_image)
    dest_image = np.zeros([range_xy[0]*32, range_xy[1]*32, 3], dtype='uint8') #uint8で作るのが大事
    for x in range(range_xy[0]):
        print x
        for y in range(range_xy[1]):
            ref_rgb = ref_image[x,y,:]
            # 一番色が近い画像を求める
#             [minind2, rss2] = findNearestColorImage(dict, ref_rgb, range(100))
#             ind3 = range(100)
            num_threashold=50
            [minind, rss] = findNearestColorImageUseMeans(dict, ref_rgb, means, num_threashold, range(10000))
            # 一番近い画像を取得
# load data
datapath = '/media/steampunkhd/rafaelvalle/datasets/MIDI/Piano'
glob_file_str = '*.npy'
n_pieces = 0  # 0 is equal to all pieces, unbalanced dataset
crop = (32, 96)
alphabet_size = 64
as_dict = False
n_steps = 64
i_len = 64
patch_size = False
inputs, labels = load_proll_data(
    datapath, glob_file_str, n_pieces, crop, as_dict, patch_size=patch_size)
labels = np.array(labels)
iterator = iterate_minibatches_proll
# shuffle data
np.random.shuffle(inputs)
BATCH_SIZE = 64
train_gen = iterator(inputs, labels, BATCH_SIZE, shuffle=True, length=i_len,
                     forever=True)
for i in range(10):
    samples, _ = train_gen.next()
    plt.imsave('real_sample_{}_o.png'.format(i),
               (samples.reshape(8, 8, alphabet_size, n_steps)
                       .transpose(0, 2, 1, 3)
                       .reshape(8*alphabet_size, 8*n_steps)), cmap='bwr')
    plt.imsave('real_sample_{}_f.png'.format(i),
               np.flipud((samples.reshape(8, 8, alphabet_size, n_steps)
                         .transpose(0, 2, 1, 3)
                         .reshape(8*alphabet_size, 8*n_steps))), cmap='bwr')
예제 #51
0
def main():
    
#     ppservers = ()
#     ppservers = ("192.168.1.242",)
    ppservers = ("192.168.1.243","192.168.1.242", )
#     job_server = pp.Server(1, ppservers=ppservers) #自PCのCPUリソース数を第一引き数で指定。0だと自PCは何もしない
    job_server = pp.Server(0, ppservers=ppservers) #自PCのCPUリソース数を第一引き数で指定。0だと自PCは何もしない
    
    # 時間測定用
    ticktock = Ticktock.Ticktock()

    # 変換元の画像
    ref_image = loadSrcImage()

    # 変換元画像を分割
    # 水平方向(X方向)に分割
#     num_separate = 1 #分割数
    num_separate = len(ppservers) #分割数
    size_x = numpy.shape(ref_image)[1]
    columns = split_seq(range(size_x), num_separate)
    ref_img_separated = []
    for i in range(num_separate):
        ref_img_separated.append(ref_image[:,columns[i],:]) 
    
    ticktock.tick() #速度測定開始

    # モザイク画作成
    jobs = []
    for i, img_in in enumerate(ref_img_separated):
        job = job_server.submit(makeMosaicImage,
                                 (img_in,),
                                 (unpickle, calMeans, getImageNum, getRGB, getPIXSIZE,
                                   getPIXNUM, findNearestColorImageUseMeans, findNearestColorImage,
                                    getColorRSSFromRGB, getRGBTable, putSmallImageOntoLargeImage,
                                     getCifar10FilePath, isExistMenaFile, getMeanFilePath, saveMeans, loadMeans, ),
                                 ("numpy","pickle")) 
        jobs.append(job)
        
    # 実行結果を得る
    dest_image = []
    for jo in jobs:
        result = jo()
#         print result
        dest_image.append(result)

    # 変換結果を結合
    dest_image_cat = [] 
    for i, img_out in enumerate(dest_image):
        if i==0:
            dest_image_cat = img_out
        else:
            dest_image_cat = numpy.hstack([dest_image_cat, img_out])
            
    ticktock.tock() #速度測定終了
    
    # レポート表示
    job_server.print_stats()
            
    
    # 保存
    pl.imsave(getResultPath() + "/dest.png", dest_image_cat)