Render an `~gwpy.types.Array2D` using `Axes.imshow`
175551
def _imshow_array2d(self, array, origin='lower', interpolation='none',
                        aspect='auto', **kwargs):
        
        # NOTE: If you change the defaults for this method, please update
        #       the docstring for `imshow` above.

        # calculate extent
        extent = tuple(array.xspan) + tuple(array.yspan)
        if self.get_xscale() == 'log' and extent[0] == 0.:
            extent = (1e-300,) + extent[1:]
        if self.get_yscale() == 'log' and extent[2] == 0.:
            extent = extent[:2] + (1e-300,) + extent[3:]
        kwargs.setdefault('extent', extent)

        return self.imshow(array.value.T, origin=origin, aspect=aspect,
                           interpolation=interpolation, **kwargs)
992985
public static INDArray convn(INDArray input, INDArray kernel, Type type, int[] axes) {
        return Nd4j.getConvolution().convn(input, kernel, type, axes);
    }
1364639
def imshow(self, canvas, X, extent=None, label=None, vmin=None, vmax=None, **kwargs):
        
        raise NotImplementedError("Implement all plot functions in AbstractPlottingLibrary in order to use your own plotting library")
310400
function render() {
    var svg = d3.select('svg');

    xAxisJoin(svg, function(d) { return [d]; })
      .attr('transform', 'translate(0, ' + (height - 20) + ')')
      .call(xAxis);

    yAxisJoin(svg, function(d) { return [d]; })
      .attr('transform', 'translate(' + (width - 30) + ', 0)')
      .call(yAxis);

    if (typeof renderComponent === 'function') {
        renderComponent();
    }
}
823319
def show_all(imgs:Collection[Image], r:int=1, c:Optional[int]=None, figsize=(12,6)):
    ""
    imgs = listify(imgs)
    if c is None: c = len(imgs)//r
    for i,ax in plot_flat(r,c,figsize): imgs[i].show(ax)
973793
public void render(float x, float y) {
		if ((sprite == null) && (defaultImageName != null)) {
			loadSystemParticleImage();
		}
		
		if (!visible) {
			return;
		}
		
		GL.glTranslatef(x,y,0);
		
		if (blendingMode == BLEND_ADDITIVE) {
			GL.glBlendFunc(SGL.GL_SRC_ALPHA, SGL.GL_ONE);
		}
		if (usePoints()) {
			GL.glEnable( SGL.GL_POINT_SMOOTH ); 
			TextureImpl.bindNone();
		}
		
		// iterate over all emitters
		for( int emitterIdx=0; emitterIdx<emitters.size(); emitterIdx++ )
		{
			// get emitter
			ParticleEmitter emitter = (ParticleEmitter) emitters.get(emitterIdx);
			
			if (!emitter.isEnabled()) {
				continue;
			}
			
			// check for additive override and enable when set
			if (emitter.useAdditive()) {
				GL.glBlendFunc(SGL.GL_SRC_ALPHA, SGL.GL_ONE);
			}
			
			// now get the particle pool for this emitter and render all particles that are in use
			ParticlePool pool = (ParticlePool) particlesByEmitter.get(emitter);
			Image image = emitter.getImage();
			if (image == null) {
				image = this.sprite;
			}
			
			if (!emitter.isOriented() && !emitter.usePoints(this)) {
				image.startUse();
			}
			
			for (int i = 0; i < pool.particles.length; i++)
			{
				if (pool.particles[i].inUse())
					pool.particles[i].render();
			} 
			
			if (!emitter.isOriented() && !emitter.usePoints(this)) {
				image.endUse();
			}

			// reset additive blend mode
			if (emitter.useAdditive()) {
				GL.glBlendFunc(SGL.GL_SRC_ALPHA, SGL.GL_ONE_MINUS_SRC_ALPHA);
			}
		}

		if (usePoints()) {
			GL.glDisable( SGL.GL_POINT_SMOOTH ); 
		}
		if (blendingMode == BLEND_ADDITIVE) {
			GL.glBlendFunc(SGL.GL_SRC_ALPHA, SGL.GL_ONE_MINUS_SRC_ALPHA);
		}
		
		Color.white.bind();
		GL.glTranslatef(-x,-y,0);
	}
36769
def image2array(image):
    
    nx, ny = image.shape  # find the size of the array
    imgh = np.reshape(image, nx*ny)  # change the shape to be 1d
    return imgh
566880
def render_image(self, rgbobj, dst_x, dst_y):
        
        pos = (0, 0)
        arr = self.viewer.getwin_array(order=self.rgb_order, alpha=1.0,
                                       dtype=np.uint8)
        #pos = (dst_x, dst_y)
        #print('dst', pos)
        #pos = self.tform['window_to_native'].to_(pos)
        #print('dst(c)', pos)
        self.gl_set_image(arr, pos)
1257748
def _image2array(filepath):
    '''
    
    '''
    im = Pimage.open(filepath).convert('RGB')
    (width, height) = im.size
    _r = np.array(list(im.getdata(0)))/255.0
    _g = np.array(list(im.getdata(1)))/255.0
    _b = np.array(list(im.getdata(2)))/255.0
    _r = _r.reshape((height, width))
    _g = _g.reshape((height, width))
    _b = _b.reshape((height, width))
    return _r, _g, _b
724891
def render(self, model, color, num_turtles):
        """"""
        self.program.bind()
        glBindVertexArray(self.vao)

        self.model_buffer.load(model.data, model.byte_size)
        self.color_buffer.load(color.data, color.byte_size)

        glDrawArraysInstanced(
            GL_TRIANGLES,
            0,
            len(self.geometry.edges) // 7,  # 7 = 4 for vertex, 3 for edge
            num_turtles
        )

        glBindVertexArray(0)
        self.program.unbind()
389245
private void renderTile(Graphic g, int tx, int ty, double viewX, double viewY)
    {
        final Tile tile = map.getTile(tx, ty);
        if (tile != null)
        {
            final int x = (int) Math.floor(tile.getX() - viewX);
            final int y = (int) Math.floor(-tile.getY() + viewY - tile.getHeight());

            for (final MapTileRenderer renderer : renderers)
            {
                renderer.renderTile(g, map, tile, x, y);
            }
        }
    }
1075946
def array_to_img(x, scale=True):
    
    from PIL import Image
    if x.ndim != 3:
        raise Exception('Unsupported shape : ', str(x.shape), '. Need (channels, width, height)')
    if scale:
        x += max(-np.min(x), 0)
        x /= np.max(x)
        x *= 255
    if x.shape[0] == 3:
        # RGB
        if x.dtype != 'uint8':
            x = x.astype('uint8')
        return Image.fromarray(x.astype('uint8'), 'RGB')
    elif x.shape[0] == 1:
        # grayscale
        if x.dtype != 'uint8':
            x = x.astype('uint8')
        return Image.fromarray(x.reshape(x.shape[1], x.shape[2]), 'L')
    else:
        raise Exception('Unsupported channel number: ', x.shape[0])
667336
def _rgbtomask(self, obj):
        """"""
        dat = obj.get_image().get_data()  # RGB arrays
        return dat.sum(axis=2).astype(np.bool)
815839
def _init_glyph(self, plot, mapping, properties):
        
        plot_method = properties.pop('plot_method', None)
        properties = mpl_to_bokeh(properties)
        data = dict(properties, **mapping)
        if self._has_holes:
            plot_method = 'multi_polygons'
        elif plot_method is None:
            plot_method = self._plot_methods.get('single')
        renderer = getattr(plot, plot_method)(**data)
        if self.colorbar:
            for k, v in list(self.handles.items()):
                if not k.endswith('color_mapper'):
                    continue
                self._draw_colorbar(plot, v, k[:-12])
        return renderer, renderer.glyph
615359
def plot_ortho_stack(images, overlays=None, reorient=True,
    # xyz arguments
    xyz=None, xyz_lines=False, xyz_color='red', xyz_alpha=0.6, xyz_linewidth=2, xyz_pad=5,
    # base image arguments
    cmap='Greys_r', alpha=1,
    # overlay arguments
    overlay_cmap='jet', overlay_alpha=0.9, 
    # background arguments
    black_bg=True, bg_thresh_quant=0.01, bg_val_quant=0.99, 
    # scale/crop/domain arguments
    crop=False, scale=False, domain_image_map=None, 
    # title arguments
    title=None, titlefontsize=24, title_dx=0, title_dy=0, 
    # 4th panel text arguemnts
    text=None, textfontsize=24, textfontcolor='white', text_dx=0, text_dy=0,
    # save & size arguments
    filename=None, dpi=500, figsize=1., colpad=0, rowpad=0,
    transpose=False, transparent=True):
    
    def mirror_matrix(x):
        return x[::-1,:]
    def rotate270_matrix(x):
        return mirror_matrix(x.T)
    def reorient_slice(x, axis):
        return rotate270_matrix(x)

    # need this hack because of a weird NaN warning from matplotlib with overlays
    warnings.simplefilter('ignore')

    n_images = len(images)

    # handle `image` argument
    for i in range(n_images):
        if isinstance(images[i], str):
            images[i] = iio2.image_read(images[i])
        if not isinstance(images[i], iio.ANTsImage):
            raise ValueError('image argument must be an ANTsImage')
        if images[i].dimension != 3:
            raise ValueError('Input image must have 3 dimensions!')

    if overlays is None:
        overlays = [None]*n_images
    # handle `overlay` argument
    for i in range(n_images):
        if overlays[i] is not None:
            if isinstance(overlays[i], str):
                overlays[i] = iio2.image_read(overlays[i])
            if not isinstance(overlays[i], iio.ANTsImage):
                raise ValueError('overlay argument must be an ANTsImage')
            if overlays[i].dimension != 3:
                raise ValueError('Overlay image must have 3 dimensions!')

            if not iio.image_physical_space_consistency(images[i], overlays[i]):
                overlays[i] = reg.resample_image_to_target(overlays[i], images[i], interp_type='linear')

    for i in range(1,n_images):
        if not iio.image_physical_space_consistency(images[0], images[i]):
            images[i] = reg.resample_image_to_target(images[0], images[i], interp_type='linear')

    # reorient images
    if reorient != False:
        if reorient == True:
            reorient = 'RPI'
        
        for i in range(n_images):
            images[i] = images[i].reorient_image2(reorient)
        
        if overlays[i] is not None:
            overlays[i] = overlays[i].reorient_image2(reorient)

    # handle `slices` argument
    if xyz is None:
        xyz = [int(s/2) for s in images[0].shape]
    for i in range(3):
        if xyz[i] is None:
            xyz[i] = int(images[0].shape[i]/2)

    # resample image if spacing is very unbalanced
    spacing = [s for i,s in enumerate(images[0].spacing)]
    if (max(spacing) / min(spacing)) > 3.:
        new_spacing = (1,1,1)
        for i in range(n_images):
            images[i] = images[i].resample_image(tuple(new_spacing))
        if overlays[i] is not None:
            overlays[i] = overlays[i].resample_image(tuple(new_spacing))
        xyz = [int(sl*(sold/snew)) for sl,sold,snew in zip(xyz,spacing,new_spacing)]

    # potentially crop image
    if crop:
        for i in range(n_images):
            plotmask = images[i].get_mask(cleanup=0)
            if plotmask.max() == 0:
                plotmask += 1
            images[i] = images[i].crop_image(plotmask)
            if overlays[i] is not None:
                overlays[i] = overlays[i].crop_image(plotmask)
                
    # pad images
    for i in range(n_images):
        if i == 0:
            images[i], lowpad, uppad = images[i].pad_image(return_padvals=True)
        else:
            images[i] = images[i].pad_image()
        if overlays[i] is not None:
            overlays[i] = overlays[i].pad_image()
    xyz = [v+l for v,l in zip(xyz,lowpad)]

    # handle `domain_image_map` argument
    if domain_image_map is not None:
        if isinstance(domain_image_map, iio.ANTsImage):
            tx = tio2.new_ants_transform(precision='float', transform_type='AffineTransform',
                                         dimension=3)
            for i in range(n_images):
                images[i] = tio.apply_ants_transform_to_image(tx, images[i], domain_image_map)
            
                if overlays[i] is not None:
                    overlays[i] = tio.apply_ants_transform_to_image(tx, overlays[i], 
                                                            domain_image_map, 
                                                            interpolation='linear')       
        elif isinstance(domain_image_map, (list, tuple)):
            # expect an image and transformation
            if len(domain_image_map) != 2:
                raise ValueError('domain_image_map list or tuple must have length == 2')
            
            dimg = domain_image_map[0]
            if not isinstance(dimg, iio.ANTsImage):
                raise ValueError('domain_image_map first entry should be ANTsImage')

            tx = domain_image_map[1]
            for i in range(n_images):
                images[i] = reg.apply_transforms(dimg, images[i], transform_list=tx)
                if overlays[i] is not None:
                    overlays[i] = reg.apply_transforms(dimg, overlays[i], transform_list=tx,
                                                   interpolator='linear')

    # potentially find dynamic range
    if scale == True:
        vmins = []
        vmaxs = []
        for i in range(n_images):
            vmin, vmax = images[i].quantile((0.05,0.95))
            vmins.append(vmin)
            vmaxs.append(vmax)
    elif isinstance(scale, (list,tuple)):
        if len(scale) != 2:
            raise ValueError('scale argument must be boolean or list/tuple with two values')
        vmins = []
        vmaxs = []
        for i in range(n_images):
            vmin, vmax = images[i].quantile(scale)
            vmins.append(vmin)
            vmaxs.append(vmax)
    else:
        vmin = None
        vmax = None

    if not transpose:
        nrow = n_images
        ncol = 3
    else:
        nrow = 3
        ncol = n_images

    fig = plt.figure(figsize=((ncol+1)*2.5*figsize, (nrow+1)*2.5*figsize))
    if title is not None:
        basey = 0.93
        basex = 0.5
        fig.suptitle(title, fontsize=titlefontsize, x=basex+title_dx, y=basey+title_dy)

    if (colpad > 0) and (rowpad > 0):
        bothgridpad = max(colpad, rowpad)
        colpad = 0
        rowpad = 0
    else:
        bothgridpad = 0.0

    gs = gridspec.GridSpec(nrow, ncol, wspace=bothgridpad, hspace=0.0,
                 top=1.-0.5/(nrow+1), bottom=0.5/(nrow+1) + colpad, 
                 left=0.5/(ncol+1) + rowpad, right=1-0.5/(ncol+1))

    # pad image to have isotropic array dimensions
    for i in range(n_images):
        images[i] = images[i].numpy()
        if overlays[i] is not None:
            overlays[i] = overlays[i].numpy()
            overlays[i][np.abs(overlays[i]) == 0] = np.nan

    ####################
    ####################
    for i in range(n_images):
        yz_slice = reorient_slice(images[i][xyz[0],:,:],0)
        if not transpose:
            ax = plt.subplot(gs[i,0])
        else:
            ax = plt.subplot(gs[0,i])
        ax.imshow(yz_slice, cmap=cmap, vmin=vmin, vmax=vmax)
        if overlays[i] is not None:
            yz_overlay = reorient_slice(overlays[i][xyz[0],:,:],0)
            ax.imshow(yz_overlay, alpha=overlay_alpha, cmap=overlay_cmap)
        if xyz_lines:
            # add lines
            l = mlines.Line2D([yz_slice.shape[0]-xyz[1],yz_slice.shape[0]-xyz[1]], 
                              [xyz_pad,yz_slice.shape[0]-xyz_pad],
                              color=xyz_color, alpha=xyz_alpha, linewidth=xyz_linewidth)
            ax.add_line(l)
            l = mlines.Line2D([xyz_pad,yz_slice.shape[1]-xyz_pad], 
                              [yz_slice.shape[1]-xyz[2],yz_slice.shape[1]-xyz[2]],
                color=xyz_color, alpha=xyz_alpha, linewidth=xyz_linewidth)
            ax.add_line(l)
        ax.axis('off')
        ####################
        ####################

        xz_slice = reorient_slice(images[i][:,xyz[1],:],1)
        if not transpose:
            ax = plt.subplot(gs[i,1])
        else:
            ax = plt.subplot(gs[1,i])
        ax.imshow(xz_slice, cmap=cmap, vmin=vmin, vmax=vmax)
        if overlays[i] is not None:
            xz_overlay = reorient_slice(overlays[i][:,xyz[1],:],1)
            ax.imshow(xz_overlay, alpha=overlay_alpha, cmap=overlay_cmap)
        if xyz_lines:
            # add lines
            l = mlines.Line2D([xz_slice.shape[0]-xyz[0],xz_slice.shape[0]-xyz[0]], 
                              [xyz_pad,xz_slice.shape[0]-xyz_pad],
                               color=xyz_color, alpha=xyz_alpha, linewidth=xyz_linewidth)
            ax.add_line(l)
            l = mlines.Line2D([xyz_pad,xz_slice.shape[1]-xyz_pad], 
                              [xz_slice.shape[1]-xyz[2],xz_slice.shape[1]-xyz[2]],
                              color=xyz_color, alpha=xyz_alpha, linewidth=xyz_linewidth)
            ax.add_line(l)
        ax.axis('off')

        ####################
        ####################
        xy_slice = reorient_slice(images[i][:,:,xyz[2]],2)
        if not transpose:
            ax = plt.subplot(gs[i,2])
        else:
            ax = plt.subplot(gs[2,i])
        ax.imshow(xy_slice, cmap=cmap, vmin=vmin, vmax=vmax)
        if overlays[i] is not None:
            xy_overlay = reorient_slice(overlays[i][:,:,xyz[2]],2)
            ax.imshow(xy_overlay, alpha=overlay_alpha, cmap=overlay_cmap)
        if xyz_lines:
            # add lines
            l = mlines.Line2D([xy_slice.shape[0]-xyz[0],xy_slice.shape[0]-xyz[0]], 
                              [xyz_pad,xy_slice.shape[0]-xyz_pad],
                              color=xyz_color, alpha=xyz_alpha, linewidth=xyz_linewidth)
            ax.add_line(l)
            l = mlines.Line2D([xyz_pad,xy_slice.shape[1]-xyz_pad], 
                              [xy_slice.shape[1]-xyz[1],xy_slice.shape[1]-xyz[1]],
                              color=xyz_color, alpha=xyz_alpha, linewidth=xyz_linewidth)
            ax.add_line(l)
        ax.axis('off')

    ####################
    ####################

    if filename is not None:
        plt.savefig(filename, dpi=dpi, transparent=transparent)
        plt.close(fig)
    else:
        plt.show()

    # turn warnings back to default
    warnings.simplefilter('default')
957138
def image_display(element, max_frames, fmt):
    
    if fmt not in Store.display_formats:
        return None
    info = process_object(element)
    if info:
        display(HTML(info))
        return

    backend = Store.current_backend
    if type(element) not in Store.registry[backend]:
        return None
    renderer = Store.renderers[backend]
    plot = renderer.get_plot(element)

    # Current renderer does not support the image format
    if fmt not in renderer.params('fig').objects:
        return None

    data, info = renderer(plot, fmt=fmt)
    return {info['mime_type']: data}, {}
392536
def vector_to_gl(array, *args):
    
    array = np.array(array)
    if len(args) > 0:
        array = np.append(array, args)
    vector = (gl.GLfloat * len(array))(*array)
    return vector