我们从Python开源项目中,提取了以下25个代码示例,用于说明如何使用pylab.gray()。
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 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 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 threshold_value(img): """ Returns a threshold value (0.9 or 0.98) based on whether any slice of the image within a central box is enterely white (white is a bitch!) 0.9 or 0.98 come simply from a lot of experimentation. """ is_color = len(img.shape) == 3 is_grey = len(img.shape) == 2 if is_color: gray = cv2.cvtColor(gray,cv2.COLOR_BGR2GRAY) elif is_grey: gray = img.copy() slices = gray.mean(axis = 1)[20:gray.shape[0]-30] is_white = any(x > 0.9*255 for x in slices) if is_white: return 0.98 else: return 0.9
def threshold_img(img): """ Simple wrap-up function for cv2.threshold() """ is_color = len(img.shape) == 3 is_grey = len(img.shape) == 2 t = threshold_value(img) if is_color: gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) elif is_grey: gray = img.copy() blurred = cv2.GaussianBlur(gray, (3, 3), 0) (_, thresh) = cv2.threshold(blurred, t*255, 1, cv2.THRESH_BINARY_INV) return thresh
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 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 bounding_box(img): """ Returns right, left, lower and upper limits for the limiting box enclosing the item (shoe, dress). Note that given the shapes and colors of some items, finding the contours and compute the bounding box is not a viable solution. """ is_color = len(img.shape) == 3 is_grey = len(img.shape) == 2 if is_color: gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) elif is_grey: gray = img.copy() slices = gray.mean(axis = 1)[20:gray.shape[0]-30] is_white = any(x > 0.9*255 for x in slices) if (is_white): h1 = min(np.apply_along_axis(get_edges, axis=0, arr=gray , thresh = 0.98)[0,:]) h2 = max(np.apply_along_axis(get_edges, axis=0, arr=gray , thresh = 0.98)[1,:]) w1 = min(np.apply_along_axis(get_edges, axis=1, arr=gray , thresh = 0.98)[:,0]) w2 = max(np.apply_along_axis(get_edges, axis=1, arr=gray , thresh = 0.98)[:,1]) else : h1 = min(np.apply_along_axis(get_edges, axis=0, arr=gray , thresh = 0.9)[0,:]) h2 = max(np.apply_along_axis(get_edges, axis=0, arr=gray , thresh = 0.9)[1,:]) w1 = min(np.apply_along_axis(get_edges, axis=1, arr=gray , thresh = 0.9)[:,0]) w2 = max(np.apply_along_axis(get_edges, axis=1, arr=gray , thresh = 0.9)[:,1]) return w1, w2, h1, h2
def shape_df(img, axis, nsteps): """ Returns a data frame with the initial and end points enclosing the product in the image, across the x/y axis. Why a dataframe and not tuples? just for convenience. """ is_color = len(img.shape) == 3 is_grey = len(img.shape) == 2 if is_color: gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) elif is_grey: gray = img.copy() edges = bounding_box(gray) gray_c = gray[edges[2]:edges[3]+1, edges[0]:edges[1]+1] thr = threshold_value(gray_c) if axis == 'x' : cuts = np.rint(np.linspace(5, gray_c.shape[1]-1, nsteps, endpoint=True)).astype(int) init = np.apply_along_axis(get_edges, 0, arr = gray_c, thresh = thr)[0,:][cuts] end = np.apply_along_axis(get_edges, 0, arr = gray_c, thresh = thr)[1,:][cuts] df = pd.DataFrame(data = {'coord' : cuts, 'init' : init, 'end' : end}, columns=['coord', 'init', 'end']) elif axis == 'y': cuts = np.round(np.linspace(4, gray_c.shape[0]-1, nsteps, endpoint=True)).astype(int) init = np.apply_along_axis(get_edges, 1, arr = gray_c, thresh = thr)[:,0][cuts] end = np.apply_along_axis(get_edges, 1, arr = gray_c, thresh = thr)[:,1][cuts] df = pd.DataFrame(data = {'coord' : cuts, 'init' : init, 'end' : end}, columns=['coord', 'init', 'end']) return df
def plot_shape(img, axis, df=None, nsteps=None): """ function to overplot the shape points onto the image img """ if df is not None and nsteps: print 'Error: provide data frame or nsteps, not both' return None if df is not None: edges = bounding_box(img) img_c = img[edges[2]:edges[3]+1, edges[0]:edges[1]+1] pyl.figure() pyl.gray() pyl.imshow(img_c) if axis == 'y': pyl.plot(df.init,df.coord, 'r*') pyl.plot(df.end, df.coord, 'r*') pyl.show() if axis == 'x': pyl.plot(df.coord,df.init, 'r*') pyl.plot(df.coord,df.end, 'r*') pyl.show() elif nsteps: pyl.figure() pyl.gray() pyl.imshow(img) if axis == 'y': df = shape_df(img, 'y', nsteps) pyl.plot(df.init,df.coord, 'r*') pyl.plot(df.end, df.coord, 'r*') pyl.show() if axis == 'x': df = shape_df(img, 'x', nsteps) pyl.plot(df.coord,df.init, 'r*') pyl.plot(df.coord,df.end, 'r*') pyl.show()
def visualiseObject(self, cmap="hot"): pylab.ion() #pylab.set_cmap("gray") pylab.gray() pylab.title("image: %s" % self.fitsFile) pylab.imshow(self.getObject(), interpolation="nearest", cmap=cmap) pylab.colorbar() pylab.ylim(-1, 2*self.extent) pylab.xlim(-1, 2*self.extent) pylab.xlabel("Pixels") pylab.ylabel("Pixels") pylab.show()
def plot_analogy(): dataset_train, dataset_test = chainer.datasets.get_mnist() images_train, labels_train = dataset_train._datasets images_test, labels_test = dataset_test._datasets dataset_indices = np.arange(0, len(images_test)) np.random.shuffle(dataset_indices) model = Model() assert model.load("model.hdf5") # normalize images_train = (images_train - 0.5) * 2 images_test = (images_test - 0.5) * 2 num_analogies = 10 pylab.gray() batch_indices = dataset_indices[:num_analogies] x_batch = images_test[batch_indices] y_batch = labels_test[batch_indices] y_onehot_batch = onehot(y_batch) with chainer.no_backprop_mode() and chainer.using_config("train", False): z_batch = model.encode_x_yz(x_batch)[1].data # plot original image on the left x_batch = (x_batch + 1.0) / 2.0 for m in range(num_analogies): pylab.subplot(num_analogies, 10 + 2, m * 12 + 1) pylab.imshow(x_batch[m].reshape((28, 28)), interpolation="none") pylab.axis("off") all_y = np.identity(10, dtype=np.float32) for m in range(num_analogies): # copy z_batch as many as the number of classes fixed_z = np.repeat(z_batch[m].reshape(1, -1), 10, axis=0) gen_x = model.decode_yz_x(all_y, fixed_z).data gen_x = (gen_x + 1.0) / 2.0 # plot images generated from each label for n in range(10): pylab.subplot(num_analogies, 10 + 2, m * 12 + 3 + n) pylab.imshow(gen_x[n].reshape((28, 28)), interpolation="none") pylab.axis("off") fig = pylab.gcf() fig.set_size_inches(num_analogies, 10) pylab.savefig("analogy.png")
def plot_analogy(): dataset_train, dataset_test = chainer.datasets.get_mnist() images_train, labels_train = dataset_train._datasets images_test, labels_test = dataset_test._datasets dataset_indices = np.arange(0, len(images_test)) np.random.shuffle(dataset_indices) model = Model() assert model.load("model.hdf5") # normalize images_train = (images_train - 0.5) * 2 images_test = (images_test - 0.5) * 2 num_analogies = 10 pylab.gray() batch_indices = dataset_indices[:num_analogies] x_batch = images_test[batch_indices] y_batch = labels_test[batch_indices] y_onehot_batch = onehot(y_batch) with chainer.no_backprop_mode() and chainer.using_config("train", False): z_batch = model.encode_x_yz(x_batch)[1].data # plot original image on the left x_batch = (x_batch + 1.0) / 2.0 for m in range(num_analogies): pylab.subplot(num_analogies, 10 + 2, m * 12 + 1) pylab.imshow(x_batch[m].reshape((28, 28)), interpolation="none") pylab.axis("off") all_y = np.identity(10, dtype=np.float32) for m in range(num_analogies): # copy z_batch as many as the number of classes fixed_z = np.repeat(z_batch[m].reshape(1, -1), 10, axis=0) representation = model.encode_yz_representation(all_y, fixed_z) gen_x = model.decode_representation_x(representation).data gen_x = (gen_x + 1.0) / 2.0 # plot images generated from each label for n in range(10): pylab.subplot(num_analogies, 10 + 2, m * 12 + 3 + n) pylab.imshow(gen_x[n].reshape((28, 28)), interpolation="none") pylab.axis("off") fig = pylab.gcf() fig.set_size_inches(num_analogies, 10) pylab.savefig("analogy.png")
def plot_analogy(): dataset_train, dataset_test = chainer.datasets.get_mnist() images_train, labels_train = dataset_train._datasets images_test, labels_test = dataset_test._datasets dataset_indices = np.arange(0, len(images_test)) np.random.shuffle(dataset_indices) model = Model() assert model.load("model.hdf5") # normalize images_train = (images_train - 0.5) * 2 images_test = (images_test - 0.5) * 2 num_analogies = 10 pylab.gray() batch_indices = dataset_indices[:num_analogies] x_batch = images_test[batch_indices] y_batch = labels_test[batch_indices] y_onehot_batch = onehot(y_batch) with chainer.no_backprop_mode() and chainer.using_config("train", False): z_batch = model.encode_x_z(x_batch).data # plot original image on the left x_batch = (x_batch + 1.0) / 2.0 for m in range(num_analogies): pylab.subplot(num_analogies, 10 + 2, m * 12 + 1) pylab.imshow(x_batch[m].reshape((28, 28)), interpolation="none") pylab.axis("off") all_y = np.identity(10, dtype=np.float32) for m in range(num_analogies): # copy z_batch as many as the number of classes fixed_z = np.repeat(z_batch[m].reshape(1, -1), 10, axis=0) gen_x = model.decode_yz_x(all_y, fixed_z).data gen_x = (gen_x + 1.0) / 2.0 # plot images generated from each label for n in range(10): pylab.subplot(num_analogies, 10 + 2, m * 12 + 3 + n) pylab.imshow(gen_x[n].reshape((28, 28)), interpolation="none") pylab.axis("off") fig = pylab.gcf() fig.set_size_inches(num_analogies, 10) pylab.savefig("analogy.png")
def plot_clusters(): dataset_train, dataset_test = chainer.datasets.get_mnist() images_train, labels_train = dataset_train._datasets images_test, labels_test = dataset_test._datasets dataset_indices = np.arange(0, len(images_test)) np.random.shuffle(dataset_indices) model = Model() assert model.load("model.hdf5") # normalize images_train = (images_train - 0.5) * 2 images_test = (images_test - 0.5) * 2 num_clusters = model.ndim_y num_plots_per_cluster = 11 image_width = 28 image_height = 28 ndim_x = image_width * image_height pylab.gray() with chainer.no_backprop_mode() and chainer.using_config("train", False): # plot cluster head head_y = np.identity(model.ndim_y, dtype=np.float32) zero_z = np.zeros((model.ndim_y, model.ndim_z), dtype=np.float32) head_x = model.decode_yz_x(head_y, zero_z).data head_x = (head_x + 1.0) / 2.0 for n in range(num_clusters): pylab.subplot(num_clusters, num_plots_per_cluster + 2, n * (num_plots_per_cluster + 2) + 1) pylab.imshow(head_x[n].reshape((image_width, image_height)), interpolation="none") pylab.axis("off") # plot elements in cluster counts = [0 for i in range(num_clusters)] indices = np.arange(len(images_test)) np.random.shuffle(indices) batchsize = 500 i = 0 x_batch = np.zeros((batchsize, ndim_x), dtype=np.float32) for n in range(len(images_test) // batchsize): for b in range(batchsize): x_batch[b] = images_test[indices[i]] i += 1 y_batch = model.encode_x_yz(x_batch)[0].data labels = np.argmax(y_batch, axis=1) for m in range(labels.size): cluster = int(labels[m]) counts[cluster] += 1 if counts[cluster] <= num_plots_per_cluster: x = (x_batch[m] + 1.0) / 2.0 pylab.subplot(num_clusters, num_plots_per_cluster + 2, cluster * (num_plots_per_cluster + 2) + 2 + counts[cluster]) pylab.imshow(x.reshape((image_width, image_height)), interpolation="none") pylab.axis("off") fig = pylab.gcf() fig.set_size_inches(num_plots_per_cluster, num_clusters) pylab.savefig("clusters.png")
def implot(result): pylab.figure(0) pylab.gray() plt.subplot(3,5,1) plt.axis('off') plt.imshow(result[0][:,:,(2,1,0)]) plt.subplot(3,5,2) plt.axis('off') plt.imshow(result[1][:,:,(2,1,0)]) plt.subplot(3,5,3) plt.axis('off') plt.imshow(result[2][:,:,(2,1,0)]) plt.subplot(3,5,4) plt.axis('off') plt.imshow(result[3][:,:,(2,1,0)]) plt.subplot(3,5,5) plt.axis('off') plt.imshow(result[4][:,:,(2,1,0)]) plt.subplot(3,5,6) plt.axis('off') plt.imshow(result[5][:,:,(2,1,0)]) plt.subplot(3,5,7) plt.axis('off') plt.imshow(result[6][:,:,(2,1,0)]) plt.subplot(3,5,8) plt.axis('off') plt.imshow(result[7][:,:,(2,1,0)]) plt.subplot(3,5,9) plt.axis('off') plt.imshow(result[8][:,:,(2,1,0)]) plt.subplot(3,5,10) plt.axis('off') plt.imshow(result[9][:,:,(2,1,0)]) plt.subplot(3,5,11) plt.axis('off') plt.imshow(result[10][:,:,(2,1,0)]) plt.subplot(3,5,12) plt.axis('off') plt.imshow(result[11][:,:,(2,1,0)]) plt.subplot(3,5,13) plt.axis('off') plt.imshow(result[12][:,:,(2,1,0)]) plt.subplot(3,5,14) plt.axis('off') plt.imshow(result[13][:,:,(2,1,0)]) plt.subplot(3,5,15) plt.axis('off') plt.imshow(result[14][:,:,(2,1,0)])
def plot(result, i, directory = 'save'): pylab.figure(0) pylab.gray() plt.subplot(3,5,1) plt.axis('off') plt.imshow(result[0][:,:,(2,1,0)]) plt.subplot(3,5,2) plt.axis('off') plt.imshow(result[1][:,:,(2,1,0)]) plt.subplot(3,5,3) plt.axis('off') plt.imshow(result[2][:,:,(2,1,0)]) plt.subplot(3,5,4) plt.axis('off') plt.imshow(result[3][:,:,(2,1,0)]) plt.subplot(3,5,5) plt.axis('off') plt.imshow(result[4][:,:,(2,1,0)]) plt.subplot(3,5,6) plt.axis('off') plt.imshow(result[5][:,:,(2,1,0)]) plt.subplot(3,5,7) plt.axis('off') plt.imshow(result[6][:,:,(2,1,0)]) plt.subplot(3,5,8) plt.axis('off') plt.imshow(result[7][:,:,(2,1,0)]) plt.subplot(3,5,9) plt.axis('off') plt.imshow(result[8][:,:,(2,1,0)]) plt.subplot(3,5,10) plt.axis('off') plt.imshow(result[9][:,:,(2,1,0)]) plt.subplot(3,5,11) plt.axis('off') plt.imshow(result[10][:,:,(2,1,0)]) plt.subplot(3,5,12) plt.axis('off') plt.imshow(result[11][:,:,(2,1,0)]) plt.subplot(3,5,13) plt.axis('off') plt.imshow(result[12][:,:,(2,1,0)]) plt.subplot(3,5,14) plt.axis('off') plt.imshow(result[13][:,:,(2,1,0)]) plt.subplot(3,5,15) plt.axis('off') plt.imshow(result[14][:,:,(2,1,0)]) plt.savefig(directory+'/'+str(i)+'.jpg')