def removeIllumination2(self, size, title = ''):
out = ndimage.filters.gaussian_filter(self.image, size)
pylab.figure()
pylab.subplot(2,2,1)
pylab.axis('off')
pylab.imshow(self.image)
pylab.subplot(2,2,2)
pylab.axis('off')
pylab.imshow(out)
pylab.subplot(2,2,3)
pylab.axis('off')
pylab.imshow(self.image - out)
pylab.subplot(2,2,4)
pylab.axis('off')
pylab.imshow(self.smooth - out)
if title != '':
pylab.savefig(title)
pylab.close()
else:
pylab.show()
self.smooth -= out
return self.image - out
python类imshow()的实例源码
def plotFields(layer,fieldShape=None,channel=None,figOffset=1,cmap=None,padding=0.01):
# Receptive Fields Summary
try:
W = layer.W
except:
W = layer
wp = W.eval().transpose();
if len(np.shape(wp)) < 4: # Fully connected layer, has no shape
fields = np.reshape(wp,list(wp.shape[0:-1])+fieldShape)
else: # Convolutional layer already has shape
features, channels, iy, ix = np.shape(wp)
if channel is not None:
fields = wp[:,channel,:,:]
else:
fields = np.reshape(wp,[features*channels,iy,ix])
perRow = int(math.floor(math.sqrt(fields.shape[0])))
perColumn = int(math.ceil(fields.shape[0]/float(perRow)))
fig = mpl.figure(figOffset); mpl.clf()
# Using image grid
from mpl_toolkits.axes_grid1 import ImageGrid
grid = ImageGrid(fig,111,nrows_ncols=(perRow,perColumn),axes_pad=padding,cbar_mode='single')
for i in range(0,np.shape(fields)[0]):
im = grid[i].imshow(fields[i],cmap=cmap);
grid.cbar_axes[0].colorbar(im)
mpl.title('%s Receptive Fields' % layer.name)
# old way
# fields2 = np.vstack([fields,np.zeros([perRow*perColumn-fields.shape[0]] + list(fields.shape[1:]))])
# tiled = []
# for i in range(0,perColumn*perRow,perColumn):
# tiled.append(np.hstack(fields2[i:i+perColumn]))
#
# tiled = np.vstack(tiled)
# mpl.figure(figOffset); mpl.clf(); mpl.imshow(tiled,cmap=cmap); mpl.title('%s Receptive Fields' % layer.name); mpl.colorbar();
mpl.figure(figOffset+1); mpl.clf(); mpl.imshow(np.sum(np.abs(fields),0),cmap=cmap); mpl.title('%s Total Absolute Input Dependency' % layer.name); mpl.colorbar()
def plotOutput(layer,feed_dict,fieldShape=None,channel=None,figOffset=1,cmap=None):
# Output summary
try:
W = layer.output
except:
W = layer
wp = W.eval(feed_dict=feed_dict);
if len(np.shape(wp)) < 4: # Fully connected layer, has no shape
temp = np.zeros(np.product(fieldShape)); temp[0:np.shape(wp.ravel())[0]] = wp.ravel()
fields = np.reshape(temp,[1]+fieldShape)
else: # Convolutional layer already has shape
wp = np.rollaxis(wp,3,0)
features, channels, iy,ix = np.shape(wp)
if channel is not None:
fields = wp[:,channel,:,:]
else:
fields = np.reshape(wp,[features*channels,iy,ix])
perRow = int(math.floor(math.sqrt(fields.shape[0])))
perColumn = int(math.ceil(fields.shape[0]/float(perRow)))
fields2 = np.vstack([fields,np.zeros([perRow*perColumn-fields.shape[0]] + list(fields.shape[1:]))])
tiled = []
for i in range(0,perColumn*perRow,perColumn):
tiled.append(np.hstack(fields2[i:i+perColumn]))
tiled = np.vstack(tiled)
if figOffset is not None:
mpl.figure(figOffset); mpl.clf();
mpl.imshow(tiled,cmap=cmap); mpl.title('%s Output' % layer.name); mpl.colorbar();
def plotFields(layer,fieldShape=None,channel=None,maxFields=25,figName='ReceptiveFields',cmap=None,padding=0.01):
# Receptive Fields Summary
W = layer.W
wp = W.eval().transpose();
if len(np.shape(wp)) < 4: # Fully connected layer, has no shape
fields = np.reshape(wp,list(wp.shape[0:-1])+fieldShape)
else: # Convolutional layer already has shape
features, channels, iy, ix = np.shape(wp)
if channel is not None:
fields = wp[:,channel,:,:]
else:
fields = np.reshape(wp,[features*channels,iy,ix])
fieldsN = min(fields.shape[0],maxFields)
perRow = int(math.floor(math.sqrt(fieldsN)))
perColumn = int(math.ceil(fieldsN/float(perRow)))
fig = mpl.figure(figName); mpl.clf()
# Using image grid
from mpl_toolkits.axes_grid1 import ImageGrid
grid = ImageGrid(fig,111,nrows_ncols=(perRow,perColumn),axes_pad=padding,cbar_mode='single')
for i in range(0,fieldsN):
im = grid[i].imshow(fields[i],cmap=cmap);
grid.cbar_axes[0].colorbar(im)
mpl.title('%s Receptive Fields' % layer.name)
# old way
# fields2 = np.vstack([fields,np.zeros([perRow*perColumn-fields.shape[0]] + list(fields.shape[1:]))])
# tiled = []
# for i in range(0,perColumn*perRow,perColumn):
# tiled.append(np.hstack(fields2[i:i+perColumn]))
#
# tiled = np.vstack(tiled)
# mpl.figure(figOffset); mpl.clf(); mpl.imshow(tiled,cmap=cmap); mpl.title('%s Receptive Fields' % layer.name); mpl.colorbar();
mpl.figure(figName+' Total'); mpl.clf(); mpl.imshow(np.sum(np.abs(fields),0),cmap=cmap); mpl.title('%s Total Absolute Input Dependency' % layer.name); mpl.colorbar()
def plotOutput(layer,feed_dict,fieldShape=None,channel=None,figOffset=1,cmap=None):
# Output summary
W = layer.output
wp = W.eval(feed_dict=feed_dict);
if len(np.shape(wp)) < 4: # Fully connected layer, has no shape
temp = np.zeros(np.product(fieldShape)); temp[0:np.shape(wp.ravel())[0]] = wp.ravel()
fields = np.reshape(temp,[1]+fieldShape)
else: # Convolutional layer already has shape
wp = np.rollaxis(wp,3,0)
features, channels, iy,ix = np.shape(wp)
if channel is not None:
fields = wp[:,channel,:,:]
else:
fields = np.reshape(wp,[features*channels,iy,ix])
perRow = int(math.floor(math.sqrt(fields.shape[0])))
perColumn = int(math.ceil(fields.shape[0]/float(perRow)))
fields2 = np.vstack([fields,np.zeros([perRow*perColumn-fields.shape[0]] + list(fields.shape[1:]))])
tiled = []
for i in range(0,perColumn*perRow,perColumn):
tiled.append(np.hstack(fields2[i:i+perColumn]))
tiled = np.vstack(tiled)
if figOffset is not None:
mpl.figure(figOffset); mpl.clf();
mpl.imshow(tiled,cmap=cmap); mpl.title('%s Output' % layer.name); mpl.colorbar();
def view_performance(file_name, triggers, lims=(150,150)):
params = CircusParser(file_name)
N_e = params.getint('data', 'N_e')
N_total = params.getint('data', 'N_total')
sampling_rate = params.getint('data', 'sampling_rate')
do_temporal_whitening = params.getboolean('whitening', 'temporal')
do_spatial_whitening = params.getboolean('whitening', 'spatial')
spike_thresh = params.getfloat('detection', 'spike_thresh')
file_out_suff = params.get('data', 'file_out_suff')
N_t = params.getint('detection', 'N_t')
nodes, edges = get_nodes_and_edges(params)
chunk_size = N_t
if do_spatial_whitening:
spatial_whitening = load_data(params, 'spatial_whitening')
if do_temporal_whitening:
temporal_whitening = load_data(params, 'temporal_whitening')
thresholds = load_data(params, 'thresholds')
try:
result = load_data(params, 'results')
except Exception:
result = {'spiketimes' : {}, 'amplitudes' : {}}
curve = numpy.zeros((len(triggers), len(result['spiketimes'].keys()), lims[1]+lims[0]), dtype=numpy.int32)
count = 0
for count, t_spike in enumerate(triggers):
for key in result['spiketimes'].keys():
elec = int(key.split('_')[1])
idx = numpy.where((result['spiketimes'][key] > t_spike - lims[0]) & (result['spiketimes'][key] < t_spike + lims[0]))
curve[count, elec, t_spike - result['spiketimes'][key][idx]] += 1
pylab.subplot(111)
pylab.imshow(numpy.mean(curve, 0), aspect='auto')
return curve
def view_whitening(data):
pylab.subplot(121)
pylab.imshow(data['spatial'], interpolation='nearest')
pylab.title('Spatial')
pylab.xlabel('# Electrode')
pylab.ylabel('# Electrode')
pylab.colorbar()
pylab.subplot(122)
pylab.title('Temporal')
pylab.plot(data['temporal'])
pylab.xlabel('Time [ms]')
x, y = pylab.xticks()
pylab.xticks(x, (x-x[-1]//2)//10)
pylab.tight_layout()
def get_performance(file_name, name):
a, b = os.path.splitext(os.path.basename(file_name))
file_name, ext = os.path.splitext(file_name)
file_out = os.path.join(os.path.abspath(file_name), a)
data = {}
result = h5py.File(file_out + '.basis.hdf5')
data['spatial'] = result.get('spatial')[:]
data['temporal'] = numpy.zeros(61) #result.get('temporal')[:]
pylab.figure()
pylab.subplot(121)
pylab.imshow(data['spatial'], interpolation='nearest')
pylab.title('Spatial')
pylab.xlabel('# Electrode')
pylab.ylabel('# Electrode')
pylab.colorbar()
pylab.subplot(122)
pylab.title('Temporal')
pylab.plot(data['temporal'])
pylab.xlabel('Time [ms]')
x, y = pylab.xticks()
pylab.xticks(x, (x-x[-1]//2)//10)
pylab.tight_layout()
plot_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '.'))
plot_path = os.path.join(plot_path, 'plots')
plot_path = os.path.join(plot_path, 'whitening')
if not os.path.exists(plot_path):
os.makedirs(plot_path)
output = os.path.join(plot_path, '%s.pdf' %name)
pylab.savefig(output)
return data
def showlabels(x,n=7):
pylab.imshow(where(x>0,x%n+1,0),cmap=pylab.cm.gist_stern)
def plotgrid(data,d=10,shape=(30,30)):
"""Plot a list of images on a grid."""
ion()
gray()
clf()
for i in range(min(d*d,len(data))):
subplot(d,d,i+1)
row = data[i]
if shape is not None: row = row.reshape(shape)
imshow(row)
ginput(1,timeout=0.1)
def showrgb(r,g=None,b=None):
if g is None: g = r
if b is None: b = r
imshow(array([r,g,b]).transpose([1,2,0]))
def showgrid(l,cols=None,n=400,titles=None,xlabels=None,ylabels=None,**kw):
if "cmap" not in kw: kw["cmap"] = cm.gray
if "interpolation" not in kw: kw["interpolation"] = "nearest"
n = minimum(n,len(l))
if cols is None: cols = int(sqrt(n))
rows = (n+cols-1)//cols
for i in range(n):
pylab.xticks([]) ;pylab.yticks([])
pylab.subplot(rows,cols,i+1)
pylab.imshow(l[i],**kw)
if titles is not None: pylab.title(str(titles[i]))
if xlabels is not None: pylab.xlabel(str(xlabels[i]))
if ylabels is not None: pylab.ylabel(str(ylabels[i]))
def edgeplot(self, TT, ps):
for ei,X in enumerate(self.edges):
(i, j) = X[:2]
Ta = TT[i]
Tb = TT[j]
plt.clf()
if len(Ta) > 1000:
nbins = 101
ra = np.hstack((Ta.ra, Tb.ra))
dec = np.hstack((Ta.dec, Tb.dec))
H,xe,ye = np.histogram2d(ra, dec, bins=nbins)
(matchRA, matchDec, dr,dd) = self.edge_matches(ei, goodonly=True)
G,xe,ye = np.histogram2d(matchRA, matchDec, bins=(xe,ye))
assert(G.shape == H.shape)
img = antigray(H / H.max())
img[G>0,:] = matplotlib.cm.hot(G[G>0] / H[G>0])
ax = setRadecAxes(xe[0], xe[-1], ye[0], ye[-1])
plt.imshow(img, extent=(min(xe), max(xe), min(ye), max(ye)),
aspect='auto', origin='lower', interpolation='nearest')
plt.axis(ax)
else:
self.plotallstars([Ta,Tb])
self.plotmatchedstars(ei)
plt.xlabel('RA (deg)')
plt.ylabel('Dec (deg)')
ps.savefig()
# one plot per edge
def plot(self, overlay_alpha=0.5):
import pylab as pl
#pl.imshow(self.image)
tinted = ((1-overlay_alpha)*self.image
+ overlay_alpha*colorize(np.argmax(self.features, 0), self.colors))
from skimage.segmentation import mark_boundaries
tinted = mark_boundaries(tinted.clip(0, 255).astype(np.uint8), np.argmax(self.features, 0))
pl.imshow(tinted)
def plot_grids(self):
import pylab as pl
pl.imshow(self.rectified)
for facade in self.facade_candidates:
facade.plot()
def plot_regions(self, fill=True, alpha=0.5):
import pylab as pl
pl.imshow(self.rectified)
for facade in self.facade_candidates:
assert isinstance(facade, FacadeCandidate)
facade.plot_regions(fill=fill, alpha=alpha)
def on_epoch_end(self, epoch, logs={}):
self.model.save_weights(os.path.join(self.output_dir, 'weights%02d.h5' % (epoch)))
self.show_edit_distance(256)
word_batch = next(self.text_img_gen)[0]
res = decode_batch(self.test_func, word_batch['the_input'][0:self.num_display_words])
if word_batch['the_input'][0].shape[0] < 256:
cols = 2
else:
cols = 1
for i in range(self.num_display_words):
pylab.subplot(self.num_display_words // cols, cols, i + 1)
if K.image_data_format() == 'channels_first':
the_input = word_batch['the_input'][i, 0, :, :]
else:
the_input = word_batch['the_input'][i, :, :, 0]
pylab.imshow(the_input.T, cmap='Greys_r')
pylab.xlabel('Truth = \'%s\'\nDecoded = \'%s\'' % (word_batch['source_str'][i], res[i]))
fig = pylab.gcf()
fig.set_size_inches(10, 13)
pylab.savefig(os.path.join(self.output_dir, 'e%02d.png' % (epoch)))
pylab.close()
def snapshot(self, fn = None, clip_ratio = None):
import matplotlib.pylab as pylab
pylab.figure(2)
self.transfer_function.show()
pylab.draw()
im = Camera.snapshot(self, fn, clip_ratio)
pylab.figure(1)
pylab.imshow(im / im.max())
pylab.draw()
self.frames.append(im)
def plot_channel(image, name, cmap='gist_heat', log=True, dex=3, zero_factor=1.0e-10,
label=None, label_color='w', label_size='large'):
"""
This function will plot a single channel. *image* is an array shaped like
(N,M), *name* is the pefix for the output filename. *cmap* is the name of
the colormap to apply, *log* is whether or not the channel should be
logged. Additionally, you may optionally specify the minimum-value cutoff
for scaling as *dex*, which is taken with respect to the minimum value of
the image. *zero_factor* applies a minimum value to all zero-valued
elements. Optionally, *label*, *label_color* and *label_size* may be
specified.
"""
import matplotlib
import pylab
Nvec = image.shape[0]
image[np.isnan(image)] = 0.0
ma = image[image>0.0].max()
image[image==0.0] = ma*zero_factor
if log:
mynorm = matplotlib.colors.LogNorm(ma/(10.**dex), ma)
pylab.clf()
pylab.gcf().set_dpi(100)
pylab.gcf().set_size_inches((Nvec/100.0, Nvec/100.0))
pylab.gcf().subplots_adjust(left=0.0, right=1.0, bottom=0.0, top=1.0, wspace=0.0, hspace=0.0)
mycm = pylab.cm.get_cmap(cmap)
if log:
pylab.imshow(image,cmap=mycm, norm=mynorm, interpolation='nearest')
else:
pylab.imshow(image,cmap=mycm, interpolation='nearest')
if label is not None:
pylab.text(20, 20,label, color = label_color, size=label_size)
pylab.savefig("%s_%s.png" % (name,cmap))
pylab.clf()
def main():
parser = buildArgsParser()
args = parser.parse_args()
# Load experiments hyperparameters
try:
hyperparams = smartutils.load_dict_from_json_file(pjoin(args.experiment, "hyperparams.json"))
except:
hyperparams = smartutils.load_dict_from_json_file(pjoin(args.experiment, '..', "hyperparams.json"))
model = load_model(args.experiment)
print(str(model))
with Timer("Generating {} samples from Conv Deep NADE".format(args.count)):
sample = model.build_sampling_function(seed=args.seed)
samples, probs = sample(args.count, return_probs=True, ordering_seed=args.seed)
if args.out is not None:
outfile = pjoin(args.experiment, args.out)
with Timer("Saving {0} samples to '{1}'".format(args.count, outfile)):
np.save(outfile, samples)
if args.view:
import pylab as plt
from convnade import vizu
if hyperparams["dataset"] == "binarized_mnist":
image_shape = (28, 28)
else:
raise ValueError("Unknown dataset: {0}".format(hyperparams["dataset"]))
plt.figure()
data = vizu.concatenate_images(samples, shape=image_shape, border_size=1, clim=(0, 1))
plt.imshow(data, cmap=plt.cm.gray, interpolation='nearest')
plt.title("Samples")
plt.figure()
data = vizu.concatenate_images(probs, shape=image_shape, border_size=1, clim=(0, 1))
plt.imshow(data, cmap=plt.cm.gray, interpolation='nearest')
plt.title("Probs")
plt.show()