def plot_rgb(image, name, label=None, label_color='w', label_size='large'):
"""
This will plot the r,g,b channels of an *image* of shape (N,M,3) or
(N,M,4). *name* is the prefix of the file name, which will be supplemented
with "_rgb.png." *label*, *label_color* and *label_size* may also be
specified.
"""
import pylab
Nvec = image.shape[0]
image[np.isnan(image)] = 0.0
if image.shape[2] >= 4:
image = image[:,:,:3]
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)
pylab.imshow(image, interpolation='nearest')
if label is not None:
pylab.text(20, 20, label, color = label_color, size=label_size)
pylab.savefig("%s_rgb.png" % name)
pylab.clf()
python类imshow()的实例源码
def plot(self,**kwargs):
"""plot landscape (kwargs are passed on to imshow()
Use interpolation='bilinear' or 'bicubic' for a smooth
surface. Default is 'nearest', which shows exact bin
boundaries.
"""
import pylab
kwargs.setdefault('interpolation','nearest')
pylab.clf()
pylab.xlabel('x')
pylab.ylabel('y')
pylab.imshow(self.pmf_masked.T,**kwargs)
pylab.colorbar()
pylab.show()
def disp(iimg, label = "", gray=False):
""" Display an image using pylab
"""
try:
import pylab
dimage = iimg.copy()
if iimg.ndim==3:
dimage[...,0] = iimg[...,2]
dimage[...,2] = iimg[...,0]
pylab.imshow(dimage, interpolation='none')
if gray: pylab.gray()
#pylab.gca().format_coord = format_coord
pylab.text(1500, -30, label)
pylab.axis('off')
pylab.show()
except ImportError:
print "Module pylab not available"
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])
for i in range(self.num_display_words):
pylab.subplot(self.num_display_words, 1, i + 1)
if K.image_dim_ordering() == 'th':
the_input = word_batch['the_input'][i, 0, :, :]
else:
the_input = word_batch['the_input'][i, :, :, 0]
pylab.imshow(the_input, cmap='Greys_r')
pylab.xlabel('Truth = \'%s\' Decoded = \'%s\'' % (word_batch['source_str'][i], res[i]))
fig = pylab.gcf()
fig.set_size_inches(10, 12)
pylab.savefig(os.path.join(self.output_dir, 'e%02d.png' % epoch))
pylab.close()
# Input Parameters
def _extract_lines(img, edges=None, mask=None, min_line_length=20, max_line_gap=3):
global __i__
__i__ += 1
if edges is None:
edges = canny(rgb2grey(img))
if mask is not None:
edges = edges & mask
# figure()
# subplot(131)
# imshow(img)
# subplot(132)
#vimshow(edges)
# subplot(133)
# if mask is not None:
# imshow(mask, cmap=cm.gray)
# savefig('/home/shared/Projects/Facades/src/data/for-labelme/debug/foo/{:06}.jpg'.format(__i__))
lines = np.array(probabilistic_hough_line(edges, line_length=min_line_length, line_gap=max_line_gap))
return lines
def plot_rectified(self):
import pylab
pylab.title('rectified')
pylab.imshow(self.rectified)
for line in self.vlines:
p0, p1 = line
p0 = self.inv_transform(p0)
p1 = self.inv_transform(p1)
pylab.plot((p0[0], p1[0]), (p0[1], p1[1]), c='green')
for line in self.hlines:
p0, p1 = line
p0 = self.inv_transform(p0)
p1 = self.inv_transform(p1)
pylab.plot((p0[0], p1[0]), (p0[1], p1[1]), c='red')
pylab.axis('image');
pylab.grid(c='yellow', lw=1)
pylab.plt.yticks(np.arange(0, self.l, 100.0));
pylab.xlim(0, self.w)
pylab.ylim(self.l, 0)
def plot_original(self):
import pylab
pylab.title('original')
pylab.imshow(self.data)
for line in self.lines:
p0, p1 = line
pylab.plot((p0[0], p1[0]), (p0[1], p1[1]), c='blue', alpha=0.3)
for line in self.vlines:
p0, p1 = line
pylab.plot((p0[0], p1[0]), (p0[1], p1[1]), c='green')
for line in self.hlines:
p0, p1 = line
pylab.plot((p0[0], p1[0]), (p0[1], p1[1]), c='red')
pylab.axis('image');
pylab.grid(c='yellow', lw=1)
pylab.plt.yticks(np.arange(0, self.l, 100.0));
pylab.xlim(0, self.w)
pylab.ylim(self.l, 0)
def plot(self):
""" Plot the layer data (for debugging)
:return: The current figure
"""
import pylab as pl
aspect = self.nrows / float(self.ncols)
figure_width = 6 #inches
rows = max(1, int(np.sqrt(self.nlayers)))
cols = int(np.ceil(self.nlayers/rows))
# noinspection PyUnresolvedReferences
pallette = {i:rgb for (i, rgb) in enumerate(pl.cm.jet(np.linspace(0, 1, 4), bytes=True))}
f, a = pl.subplots(rows, cols)
f.set_size_inches(6 * cols, 6 * rows)
a = a.flatten()
for i, label in enumerate(self.label_names):
pl.sca(a[i])
pl.title(label)
pl.imshow(self.color_data)
pl.imshow(colorize(self.label_data[:, :, i], pallette), alpha=0.5)
# axis('off')
return f
def plot(self, overlay_alpha=0.5):
import pylab as pl
rows = int(sqrt(self.layers()))
cols = int(ceil(self.layers()/rows))
for i in range(rows*cols):
pl.subplot(rows, cols, i+1)
pl.axis('off')
if i >= self.layers():
continue
pl.title('{}({})'.format(self.labels[i], i))
pl.imshow(self.image)
pl.imshow(colorize(self.features[i].argmax(0),
colors=np.array([[0, 0, 255],
[0, 255, 255],
[255, 255, 0],
[255, 0, 0]])),
alpha=overlay_alpha)
def _plot_background(self, bgimage):
import pylab as pl
# Show the portion of the image behind this facade
left, right = self.facade_left, self.facade_right
top, bottom = 0, self.mega_facade.rectified.shape[0]
if bgimage is not None:
pl.imshow(bgimage[top:bottom, left:right], extent=(left, right, bottom, top))
else:
# Fit the facade in the plot
y0, y1 = pl.ylim()
x0, x1 = pl.xlim()
x0 = min(x0, left)
x1 = max(x1, right)
y0 = min(y0, top)
y1 = max(y1, bottom)
pl.xlim(x0, x1)
pl.ylim(y1, y0)
def show_mpl(self, im, enhance=True, clear_fig=True):
if self._pylab is None:
import pylab
self._pylab = pylab
if self._render_figure is None:
self._render_figure = self._pylab.figure(1)
if clear_fig: self._render_figure.clf()
if enhance:
nz = im[im > 0.0]
nim = im / (nz.mean() + 6.0 * np.std(nz))
nim[nim > 1.0] = 1.0
nim[nim < 0.0] = 0.0
del nz
else:
nim = im
ax = self._pylab.imshow(nim[:,:,:3]/nim[:,:,:3].max(), origin='upper')
return ax
def plot_allsky_healpix(image, nside, fn, label = "", rotation = None,
take_log = True, resolution=512, cmin=None, cmax=None):
import matplotlib.figure
import matplotlib.backends.backend_agg
if rotation is None: rotation = np.eye(3).astype("float64")
img, count = pixelize_healpix(nside, image, resolution, resolution, rotation)
fig = matplotlib.figure.Figure((10, 5))
ax = fig.add_subplot(1,1,1,projection='aitoff')
if take_log: func = np.log10
else: func = lambda a: a
implot = ax.imshow(func(img), extent=(-np.pi,np.pi,-np.pi/2,np.pi/2),
clip_on=False, aspect=0.5, vmin=cmin, vmax=cmax)
cb = fig.colorbar(implot, orientation='horizontal')
cb.set_label(label)
ax.xaxis.set_ticks(())
ax.yaxis.set_ticks(())
canvas = matplotlib.backends.backend_agg.FigureCanvasAgg(fig)
canvas.print_figure(fn)
return img, count
def interpolate2dDiffusion(arr1, arr2, steps=10, diffusivity=0.2):
psf = np.zeros((5, 5))
numbaGaussian2d(psf, 1, 1)
# plt.imshow(psf)
# plt.show()
last = arr1
out = []
for s in range(steps):
next = np.zeros_like(arr1)
diff = diffusivity * (last - arr2)
# plt.imshow(diff)
# plt.show()
weightedConvolution(last, next, diff, psf)
out.append(next)
last = next
return out
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_dim_ordering() == 'th':
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 train(sentences,discriminator_gen=discriminator_gen,discriminator=discriminator,gen_model=gen_model):
data,real_word=getData(sentences)
fake_word=gen_model.predict(data)
pylab.imshow(fake_word[0][0], cmap=cm.Greens,origin='lower')
real_label=np.zeros((1,))
fake_label=np.ones((1,))
#discriminator.predict(real_word)
discriminator_gen.fit(data,fake_label,nb_epoch=5)
fake_word=gen_model.predict(data)
discriminator.fit(fake_word,real_label,nb_epoch=5)
discriminator.fit(real_word,fake_label,nb_epoch=5)
image_ocr_gpu.py 文件源码
项目:keras-mxnet-benchmarks
作者: sandeep-krishnamurthy
项目源码
文件源码
阅读 22
收藏 0
点赞 0
评论 0
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_dim_ordering() == 'th':
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 tile_images(image_batch, image_width=28, image_height=28, image_channel=1, dir=None, filename="images"):
if dir is None:
raise Exception()
try:
os.mkdir(dir)
except:
pass
fig = pylab.gcf()
fig.set_size_inches(16.0, 16.0)
pylab.clf()
pylab.gray()
for m in range(100):
pylab.subplot(10, 10, m + 1)
pylab.imshow(image_batch[m].reshape((image_width, image_height)), interpolation="none")
pylab.axis("off")
pylab.savefig("{}/{}.png".format(dir, filename))
def view_(_pred,_lable):
fname = ['Captcha/lv3/%i.jpg' %i for i in range(20)]
img = []
for fn in fname:
img.append(Image.open(open(fn)))
#img.append(misc.imread(fn).astype(np.float))
for i in range(len(img)):
pylab.subplot(4,5,i+1); pylab.axis('off')
pylab.imshow(img[i])
#pylab.imshow( np.dot(np.array(img[i])[...,:3],[0.299,0.587,0.114]) , cmap=plt.get_cmap("gray"))
#pylab.text(40,60,_pred[i],color = 'b')
if ( _pred[i] == _lable[i] ):
pylab.text(40,65,_pred[i],color = 'b',size = 15)
else:
pylab.text(40,65,_pred[i],color = 'r',size = 15)
pylab.text(40,92,_lable[i],color = 'g',size = 15)
pylab.show()
def visualize_reconstruction(xp, model, x, visualization_dir, epoch, gpu=False):
x_variable = chainer.Variable(xp.asarray(x))
_x = model.decode(model.encode(x_variable), test=True)
_x.to_cpu()
_x = _x.data
fig = pylab.gcf()
fig.set_size_inches(8.0, 8.0)
pylab.clf()
pylab.gray()
for m in range(50):
i = m / 10
j = m % 10
pylab.subplot(10, 10, 20 * i + j + 1, xticks=[], yticks=[])
pylab.imshow(x[m].reshape((28, 28)), interpolation="none")
pylab.subplot(10, 10, 20 * i + j + 10 + 1, xticks=[], yticks=[])
pylab.imshow(_x[m].reshape((28, 28)), interpolation="none")
# pylab.imshow(np.clip((_x_batch.data[m] + 1.0) / 2.0, 0.0, 1.0).reshape(
# (config.img_channel, config.img_width, config.img_width)), interpolation="none")
pylab.axis("off")
pylab.savefig("{}/reconstruction_{}.png".format(visualization_dir, epoch))
# pylab.show()
def plot_2D_heat_map(states,p,labels, inter=False):
import pylab as pl
X = np.unique(states[0,:])
Y = np.unique(states[1,:])
X_len = len(X)
Y_len = len(Y)
Z = np.zeros((X.max()+1,Y.max()+1))
for i in range(len(p)):
Z[states[0,i],states[1,i]] = p[i]
pl.clf()
pl.imshow(Z.T, origin='lower')
pl.xlabel(labels[0])
pl.ylabel(labels[1])
if inter== True:
pl.draw()
else:
pl.show()
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_dim_ordering() == 'th':
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 tile_binary_images(x, dir=None, filename="x", row=10, col=10):
if dir is None:
raise Exception()
try:
os.mkdir(dir)
except:
pass
fig = pylab.gcf()
fig.set_size_inches(col * 2, row * 2)
pylab.clf()
pylab.gray()
for m in range(row * col):
pylab.subplot(row, col, m + 1)
pylab.imshow(np.clip(x[m], 0, 1), interpolation="none")
pylab.axis("off")
pylab.savefig("{}/{}.png".format(dir, filename))
def visualiseNormObject(self):
shape = (2*self.extent, 2*self.extent)
pylab.ion()
pylab.clf()
#pylab.set_cmap("bone")
pylab.hot()
pylab.title("image: %s" % self.fitsFile)
pylab.imshow(np.reshape(self.signPreserveNorm(), shape, order="F"), interpolation="nearest")
pylab.plot(np.arange(0,2*self.extent), self.extent*np.ones((2*self.extent,)), "r--")
pylab.plot(self.extent*np.ones((2*self.extent,)), np.arange(0,2*self.extent), "r--")
pylab.colorbar()
pylab.ylim(-1, 2*self.extent)
pylab.xlim(-1, 2*self.extent)
pylab.xlabel("Pixels")
pylab.ylabel("Pixels")
pylab.show()
def visualiseNormObject(self):
shape = (2*self.extent, 2*self.extent)
pylab.ion()
pylab.clf()
#pylab.set_cmap("bone")
pylab.hot()
pylab.title("image: %s" % self.fitsFile)
pylab.imshow(np.reshape(self.signPreserveNorm(), shape, order="F"), interpolation="nearest")
pylab.plot(np.arange(0,2*self.extent), self.extent*np.ones((2*self.extent,)), "r--")
pylab.plot(self.extent*np.ones((2*self.extent,)), np.arange(0,2*self.extent), "r--")
pylab.colorbar()
pylab.ylim(-1, 2*self.extent)
pylab.xlim(-1, 2*self.extent)
pylab.xlabel("Pixels")
pylab.ylabel("Pixels")
pylab.show()
def tile_binary_images(x, dir=None, filename="x", row=10, col=10):
if dir is None:
raise Exception()
try:
os.mkdir(dir)
except:
pass
fig = pylab.gcf()
fig.set_size_inches(col * 2, row * 2)
pylab.clf()
pylab.gray()
for m in range(row * col):
pylab.subplot(row, col, m + 1)
pylab.imshow(np.clip(x[m], 0, 1), interpolation="none")
pylab.axis("off")
pylab.savefig("{}/{}.png".format(dir, filename))
def tile_binary_images(x, dir=None, filename="x"):
if dir is None:
raise Exception()
try:
os.mkdir(dir)
except:
pass
fig = pylab.gcf()
fig.set_size_inches(16.0, 16.0)
pylab.clf()
pylab.gray()
for m in range(100):
pylab.subplot(10, 10, m + 1)
pylab.imshow(np.clip(x[m], 0, 1), interpolation="none")
pylab.axis("off")
pylab.savefig("{}/{}.png".format(dir, filename))
def generate(self, filename, show=True):
'''Generate a sample sequence, plot the resulting piano-roll and save
it as a MIDI file.
filename : string
A MIDI file will be created at this location.
show : boolean
If True, a piano-roll of the generated sequence will be shown.'''
piano_roll = self.generate_function()
midiwrite(filename, piano_roll, self.r, self.dt)
if show:
extent = (0, self.dt * len(piano_roll)) + self.r
pylab.figure()
pylab.imshow(piano_roll.T, origin='lower', aspect='auto',
interpolation='nearest', cmap=pylab.cm.gray_r,
extent=extent)
pylab.xlabel('time (s)')
pylab.ylabel('MIDI note number')
pylab.title('generated piano-roll')
def visualize_x(reconstructed_x_batch, image_width=28, image_height=28, image_channel=1, dir=None):
if dir is None:
raise Exception()
try:
os.mkdir(dir)
except:
pass
fig = pylab.gcf()
fig.set_size_inches(16.0, 16.0)
pylab.clf()
if image_channel == 1:
pylab.gray()
for m in range(100):
pylab.subplot(10, 10, m + 1)
if image_channel == 1:
pylab.imshow(reconstructed_x_batch[m].reshape((image_width, image_height)), interpolation="none")
elif image_channel == 3:
pylab.imshow(reconstructed_x_batch[m].reshape((image_channel, image_width, image_height)), interpolation="none")
pylab.axis("off")
pylab.savefig("%s/reconstructed_x.png" % dir)
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_dim_ordering() == 'th':
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 convert16to8(self, smooth = False):
if smooth:
matout = self.smooth
else:
matout = self.image
p = np.percentile(matout, 98)
lowp = np.percentile(matout, 1)
matout -= lowp
if p == 0:
p = np.max(matout)
#print lowp, p, np.max(matout)
matout[matout < 0] = 0
matout[matout > p] = p
#pylab.imshow(matout/p*255, 'gray')
#pylab.show()
return np.array(matout/p*255, np.uint8)