Example #1
0
def tmp(cm, acts):
    import matplotlib.pyplot as plt
    import numpy as np

    plt.imshow(cm, interpolation='nearest')
    plt.xticks(np.arange(0, len(acts)), acts)
    plt.yticks(np.arange(0, len(acts)), acts)
def test_psv_dataset_tfm_segmentation_cropped():
    from psv.ptdataset import PsvDataset, TFM_SEGMENTATION_CROPPED

    ds = PsvDataset(transform=TFM_SEGMENTATION_CROPPED)

    assert len(ds) == 956, "The dataset should have this many entries"

    mb = ds[0]
    image = mb['image']
    mask = mb['mask']
    assert isinstance(image, torch.Tensor)
    assert isinstance(mask, torch.Tensor)

    assert mask.shape[-2:] == image.shape[-2:]

    # Hard to test due to randomness....

    PLOT=True
    if PLOT:
        from matplotlib.pylab import plt
        import torchvision.transforms.functional as F
        a = ds.get_annotation(0)
        plt.figure()
        plt.suptitle('Visualizing test_psv_dataset_tfm_segmentation_cropped, close if ok')
        plt.subplot(121)
        plt.imshow(F.to_pil_image(image))
        plt.title('image')

        plt.subplot(122)
        plt.imshow(a.colors[mask.numpy()])
        plt.title('mask')
        plt.show()
def test_psv_dataset_crop_and_pad():
    import psv.ptdataset as P


    TFM_SEGMENTATION_CROPPED = psv.transforms.Compose(
        psv.transforms.ToSegmentation(),

        # Crop in on the facades
        psv.transforms.SetCropToFacades(pad=20, pad_units='percent', skip_unlabeled=True, minsize=(512, 512)),
        psv.transforms.ApplyCrop('image'),
        psv.transforms.ApplyCrop('mask'),
        
        # Resize the height to fit in the net (with some wiggle room)
        # THIS is the test case -- the crops will not usually fit anymore
        psv.transforms.Resize('image', height=400),
        psv.transforms.Resize('mask', height=400, interpolation=P.Image.NEAREST),

        # Reandomly choose a subimage
        psv.transforms.SetRandomCrop(512, 512),
        psv.transforms.ApplyCrop('image'),
        psv.transforms.ApplyCrop('mask', fill=24), # 24 should be unlabeled
        
        psv.transforms.DropKey('annotation'),
        psv.transforms.ToTensor('image'),
        psv.transforms.ToTensor('mask', preserve_range=True),
        ) 

    ds = P.PsvDataset(transform=TFM_SEGMENTATION_CROPPED)

    assert len(ds) == 956, "The dataset should have this many entries"

    mb = ds[0]
    image = mb['image']
    mask = mb['mask']
    assert isinstance(image, torch.Tensor)
    assert isinstance(mask, torch.Tensor)

    assert mask.shape[-2:] == image.shape[-2:]

    # Hard to test due to randomness....

    PLOT=True
    if PLOT:
        from matplotlib.pylab import plt
        import torchvision.transforms.functional as F
        a = ds.get_annotation(0)
        plt.figure()
        plt.suptitle('Visualizing test_psv_dataset_tfm_segmentation_cropped,\n'
                     'close if ok \n '
                     'confirm boundary is  marked unlabeled')
        plt.subplot(121)
        plt.imshow(F.to_pil_image(image))
        plt.title('image')

        plt.subplot(122)
        plt.imshow(a.colors[mask.numpy()])
        plt.title('mask')
        plt.show()
def plot_gallery(images, titles, h, w, n_row=3,n_col=4):
    plt.figure(figsize=(1.8*n_col, 2.4*n_row))
    plt.subplots_adjust(bottom=0,left=.01,right=.99,top=.90,hspace=.35)
    for i in range(n_row * n_col):
        plt.subplot(n_row,n_col,i+1)
        plt.imshow(images[i].reshape(h,w),cmap=plt.cm.gray)
        plt.title(titles[i],size=12)
        plt.xticks(())
        plt.yticks(())
def display_digit(X_data, y_data=None, i=0):
    """Display the Xi image, optionally with the corresponding yi label."""
    plt.close('all')
    Xi = X_data[i]
    side = np.sqrt(Xi.size).astype(int)
    data = np.array(Xi).reshape((side, side))
    plt.imshow(data, cmap='Greys', interpolation='nearest')
    plt.title("y = " + str(y_data[i]))
    plt.show()
Example #6
0
 def f(self, **kwargs):
     kwargs['always_apply'] = True
     print(kwargs)
     aug = self.tfms(**kwargs)
     #         Just copy all images, next step will be for continious albus
     image = aug(image=self.image.copy())['image']
     plt.figure(figsize=(10, 10))
     plt.imshow(image)
     plt.axis('off')
     plt.show()
Example #7
0
 def plotMagnitudePhaseImage(self, image):
     mag = absolute(image).astype('float')
     phase = angle(image).astype('float')
     
     plt.subplot(211)
     plt.imshow(mag, cmap = cm.Greys_r)
     plt.axis('off')
     plt.subplot(212)
     plt.imshow(phase, cmap = cm.Greys_r)
     plt.axis('off')
     plt.show()
Example #8
0
def Brightness_map(image, image_name):
	# map = (image[:, :, 0] + image[:, :, 1] + image[:, :, 2]) / 3
	map = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
	map = map.reshape(image.shape[0] * image.shape[1], 1)

	km = KMeans(n_clusters=16).fit(map)
	map = km.labels_.reshape(image.shape[0], image.shape[1])
	plt.imshow(map / map.max(), cmap='gray')
	plt.axis('off')
	plt.savefig(image_name + '_brightness_map')
	np.save(image_name + '_brightness_map.npy', map)
Example #9
0
    def saveMagPhaseImage(self, image, filename):
        mag = absolute(image).astype('float')
        phase = angle(image).astype('float')

        plt.subplot(211)
        plt.imshow(mag, cmap=cm.Greys_r)
        plt.title('Magnitude')
        plt.axis('off')
        plt.subplot(212)
        plt.imshow(phase, cmap=cm.Greys_r)
        plt.title('Phase')
        plt.axis('off')
        plt.savefig(filename)
Example #10
0
def texture_ID(image, map, image_name):

	for ch in range(3):
		channel = map[:, :, ch, :]
		channel = channel.reshape(image.shape[0] * image.shape[1], map.shape[-1])
		km = KMeans(n_clusters=64).fit(channel)
		T_channel = km.labels_.reshape(image.shape[0], image.shape[1])
		image[:, :, ch] = T_channel

	plt.imshow(image/image.max())
	plt.axis('off')
	plt.savefig(image_name + '_texture_map')
	np.save(image_name + '_texture_map.npy', image)
Example #11
0
def save_plot(filter_bank, name):

	rows , cols = filter_bank.shape[0:2]

	plt.figure()
	sub = 1
	for row in range(rows):
		for col in range(cols):
			plt.subplot(rows, cols, sub)
			plt.imshow(filter_bank[row][col], cmap='gray')
			plt.axis('off')
			sub += 1

	plt.savefig(name)
Example #12
0
def Color_map(image, image_name):

	for ch in range(3):
		channel = image[:, :, ch]
		channel = channel.reshape(image.shape[0] * image.shape[1], 1)
		km = KMeans(n_clusters=16).fit(channel)
		T_channel = km.labels_.reshape(image.shape[0], image.shape[1])
		image[:, :, ch] = T_channel

	plt.imshow(image / image.max())
	plt.axis('off')
	plt.savefig(image_name + '_color_map')

	np.save(image_name + '_color_map.npy', image)
Example #13
0
def Gradient(image_name, map_name):
	mask_filters = Half_disk_masks(3, 8, plot=False)
	map = np.load(image_name + '_' + map_name + '_map.npy')
	# plt.imshow(map / map.max(), cmap='gray')
	# plt.savefig(image_name + '_map')
	gradients = []


	for row in range(3):
		for col in range(4):
			left_mask = mask_filters[row][2 * col]
			right_mask = mask_filters[row][2 * col + 1]
			chi_sqr_dist = map * 0
			k = map.max() + 1
			for bin in range(k):
				bin_chi_dist = map * 0
				temp = np.sign(-1 * (map - bin)) + 1

				g_i = cv2.filter2D(temp, -1, left_mask)
				h_i = cv2.filter2D(temp, -1, right_mask)

				num = np.square(h_i - g_i)
				denom = 1. / (g_i + h_i + 0.000005)
				bin_chi_dist = np.multiply(num, denom)


				# for x in range(temp.shape[0]):
				# 	for y in range(temp.shape[1]):
				# 		for z in range(temp.shape[2]):
				# 			if g_i[x][y][z] + h_i[x][y][z] != 0:
				# 				bin_chi_dist[x][y][z] = (g_i[x][y][z] - h_i[x][y][z]) ** 2 / (g_i[x][y][z] + h_i[x][y][z])


				chi_sqr_dist = chi_sqr_dist + bin_chi_dist / k

			gradients.append(chi_sqr_dist)

	gradient_map = np.mean(np.array(gradients), axis=0)

	if map_name == 'brightness':
		plt.imshow(gradient_map / gradient_map.max(), cmap='gray')
	else:
		plt.imshow(gradient_map / gradient_map.max())
	plt.axis('off')
	plt.savefig(image_name + '_' + map_name + '_gradient_map')
	np.save(image_name + '_' + map_name + '_gradient.npy', gradient_map)
 def show_failures(self, x_test, t_test):
     y = self.predict(x_test)
     y = np.argmax(y, axis=1)
     if t_test.ndim != 1: t_test = np.argmax(t_test, axis=1)
     failures = []
     for idx in range(x_test.shape[0]):
         if y[idx] != t_test[idx]:
             failures.append((x_test[idx], y[idx], t_test[idx]))
     for i in range(min(len(failures), 60)):
         img, y, _ = failures[i]
         if (i % 10 == 0): print()
         print(y, end=", ")
         img = img.reshape(28, 28)
         plt.subplot(6, 10, i + 1)
         plt.imshow(img, cmap='gray')
     print()
     plt.show()
Example #15
0
def visualize(img, G, vertices):
    plt.imshow(img, cmap='gray')

    # draw edges by pts
    for (s, e) in G.edges():
        vals = flatten([[v] for v in G[s][e].values()])
        for val in vals:
            ps = val.get('pts', [])
            plt.plot(ps[:, 1], ps[:, 0], 'green')

    # draw node by o
    node, nodes = G.node(), G.nodes
    # deg = G.degree
    # ps = np.array([node[i]['o'] for i in nodes])
    ps = np.array(vertices)
    plt.plot(ps[:, 1], ps[:, 0], 'r.')

    # title and show
    plt.title('Build Graph')
    plt.show()
Example #16
0
def visualize(img, G, vertices):
    plt.imshow(img, cmap='gray')

    # draw edges by pts
    for (s, e) in G.edges():
        vals = flatten([[v] for v in G[s][e].values()])
        for val in vals:
            ps = val.get('pts', [])
            plt.plot(ps[:, 1], ps[:, 0], 'green')

    # draw node by o
    node, nodes = G.node(), G.nodes
    # deg = G.degree
    # ps = np.array([node[i]['o'] for i in nodes])
    ps = np.array(vertices)
    plt.plot(ps[:, 1], ps[:, 0], 'r.')

    # title and show
    plt.title('Build Graph')
    plt.show()
Example #17
0
def augmentation_visualize_and_save(config,
                                    images,
                                    images_names,
                                    path,
                                    times: int = 2):
    """
    Visualization of image enhancements.
    :param config: configuration from yaml file.
    :param images: images to be augmented.
    :param images_names: corresponding names of the images.
    :param path: the root where the augmented pictures will be saved.
    :param times: how many times each image getting augmented.
    :return:
    """

    rows = len(images)
    cols = times + 1
    for (index, image), name in zip(enumerate(images), images_names):
        plt.subplot(rows, cols, index * cols + 1)
        plt.axis('off')
        plt.title(name)
        _image = bgr2rgb_using_opencv(image)
        plt.imshow(_image)
        for col in range(1, cols):
            plt.subplot(rows, cols, index * cols + col + 1)
            plt.axis('off')
            plt.title("Augmented NO. " + str(col))
            # augment image
            augmented_image = augment_image_using_imgaug(_image, config)
            plt.imshow(augmented_image)

    # Save the full figure
    isExists = os.path.exists(path)
    if not isExists:
        os.makedirs(path)
    now_time = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
    savefig(os.path.join(path, "%s_Comp.png" % now_time), dpi=600)
    # Clear the current figure
    plt.clf()
    plt.cla()
    plt.close()
Example #18
0
def pb_lite(Sobel, Canny, image_name):
	B = np.load(image_name + '_brightness_gradient.npy')
	T = np.load(image_name + '_texture_gradient.npy')
	C = np.load(image_name + '_color_gradient.npy')

	B / B.max()
	T / T.max()
	C / C.max()



	w1 = 0.5
	w2 = 0.5
	features = (B + rgb2gray(T) + rgb2gray(C))/3
	average = w1 * Canny + w2 * Sobel
	pb_edge = features * rgb2gray(average)

	plt.imshow(pb_edge, cmap='gray')
	plt.savefig(image_name + '_pb_edge')

	s = 1
Example #19
0
def visualize(img, G, vertices, fn):
    plt.imshow(img)

    # draw edges by pts
    for (s, e) in G.edges():
        vals = flatten([[v] for v in G[s][e].values()])
        for val in vals:
            ps = val.get('pts', [])
            plt.plot(ps[:, 1], ps[:, 0], 'green')

    # draw node by o
    #node, nodes = G.node(), G.nodes
    # deg = G.degree
    # ps = np.array([node[i]['o'] for i in nodes])
    ps = np.array(vertices)
    plt.plot(ps[:, 1], ps[:, 0], 'r.')

    # title and show
    img_name = fn.split('.')[0] + ".png"
    map_name = fn.split('.')[0] + "_roads.png"
    io.imsave(img_name, img)
    plt.savefig(map_name)
Example #20
0
def reduce_opacity(image, opacity):
    assert opacity >= 0 and opacity <= 1

    if image.mode != 'RGBA':
        image = image.convert('RGBA')
    else:
        image = image.copy()

    alpha = image.split()
    for i in alpha:
        plt.imshow(i)
        plt.show()

    # print type(alpha)
    # alpha = ImageEnhance.Brightness(alpha).enhance(opacity)
    # print alpha
    # image = image.putalpha(alpha)
    # print image
    # plt.imshow(image)
    # plt.show()
    # image.save("hahaha.JPG")
    image.getpixel((0, 0))
    return image
Example #21
0
    def plotting(self, pressurelattice, invasionlattice, pressure,
                 number_of_clusters):

        from matplotlib.pylab import plt

        #Plotting the invasionlattice
        plt.figure(2)
        plt.imshow(invasionlattice, cmap='Greys', interpolation='nearest')
        plt.title("Invasion lattice")
        plt.colorbar()
        plt.savefig(self.pathsimulation + "invasionlattice.png",
                    bbox_inches="tight")
        plt.close()

        #plotting the pressure
        plt.figure(5)
        plt.plot(pressure)
        plt.xlabel('Time')
        plt.ylabel('Pressure')
        plt.title('P(t)')
        plt.savefig(self.pathsimulation + "pressure.png", bbox_inches="tight")
        plt.close()

        #plotting the clusterlattice
        plt.figure(6)
        plt.imshow(self.lw, interpolation='nearest')
        plt.title("Clusterlattice")
        plt.colorbar()
        plt.savefig(self.pathsimulation + "clusterlattice.png",
                    bbox_inches="tight")
        plt.close()

        #Temporal diagram
        plt.figure(7)
        plt.imshow(self.temporalplot, interpolation='nearest')
        plt.title('Temporal diagram')
        plt.colorbar()
        plt.savefig(self.pathsimulation + "temporal.png", bbox_inches="tight")
        plt.close()

        #Plotting pressure distribution in the cell.
        plt.figure(3)
        plt.hist(pressurelattice.ravel(), bins=30, fc='k', ec='k')
        plt.savefig(self.pathsimulation + "pressuredistribution.png",
                    bbox_inches="tight")
        plt.close()

        #Plotting the number of clusters as a function of interation.
        plt.figure(1)
        plt.plot(number_of_clusters)
        plt.xlabel('Iteration number/time')
        plt.ylabel('Number of clusters')
        plt.title('Number_of_cluster(t)')
        plt.savefig(self.pathsimulation + "clusterN.png", bbox_inches="tight")
        plt.close()
Example #22
0
	def plotting(self,pressurelattice,invasionlattice,pressure,number_of_clusters):

		from matplotlib.pylab import plt

		#Plotting the invasionlattice
		plt.figure(2)
		plt.imshow(invasionlattice, cmap='Greys',interpolation='nearest')
		plt.title("Invasion lattice")
		plt.colorbar()
		plt.savefig(self.pathsimulation + "invasionlattice.png", bbox_inches="tight")
		plt.close()

		#plotting the pressure
		plt.figure(5)
		plt.plot(pressure)
		plt.xlabel('Time')
		plt.ylabel('Pressure')
		plt.title('P(t)')
		plt.savefig(self.pathsimulation +"pressure.png", bbox_inches="tight")
		plt.close()

		#plotting the clusterlattice
		plt.figure(6)
		plt.imshow(self.lw, interpolation='nearest')
		plt.title("Clusterlattice")
		plt.colorbar()
		plt.savefig(self.pathsimulation +"clusterlattice.png", bbox_inches="tight")
		plt.close()

		#Temporal diagram
		plt.figure(7)
		plt.imshow(self.temporalplot,interpolation='nearest')
		plt.title('Temporal diagram')
		plt.colorbar()
		plt.savefig(self.pathsimulation +"temporal.png", bbox_inches="tight")
		plt.close()

		#Plotting pressure distribution in the cell.
		plt.figure(3)
		plt.hist(pressurelattice.ravel(), bins=30, fc='k', ec='k')
		plt.savefig(self.pathsimulation +"pressuredistribution.png", bbox_inches="tight")
		plt.close()

		#Plotting the number of clusters as a function of interation.
		plt.figure(1)
		plt.plot(number_of_clusters)
		plt.xlabel('Iteration number/time')
		plt.ylabel('Number of clusters')
		plt.title('Number_of_cluster(t)')
		plt.savefig(self.pathsimulation +"clusterN.png", bbox_inches="tight")
		plt.close()
Example #23
0
    def saveWaterFatImage(self, filename):
        mag = np.absolute(self.water).astype('float')
        phase = np.angle(self.water).astype('float')
        mag2 = np.absolute(self.fat).astype('float')
        phase2 = np.angle(self.fat).astype('float')

        plt.subplot(221)
        plt.imshow(mag, cmap=cm.Greys_r)
        plt.title('Water Magnitude')
        plt.axis('off')
        plt.subplot(222)
        plt.imshow(phase, cmap=cm.Greys_r)
        plt.title('Water Phase')
        plt.axis('off')
        plt.subplot(223)
        plt.imshow(mag2, cmap=cm.Greys_r)
        plt.title('Fat Magnitude')
        plt.axis('off')
        plt.subplot(224)
        plt.imshow(phase2, cmap=cm.Greys_r)
        plt.title('Fat Phase')
        plt.axis('off')
        plt.show()
Example #24
0
    def saveMagPhaseImage2(self, image1, image2, filename):
        mag = absolute(image1).astype('float')
        phase = angle(image1).astype('float')
        mag2 = absolute(image2).astype('float')
        phase2 = angle(image2).astype('float')

        plt.subplot(221)
        plt.imshow(mag, cmap=cm.Greys_r)
        plt.title('Magnitude')
        plt.axis('off')
        plt.subplot(222)
        plt.imshow(phase, cmap=cm.Greys_r)
        plt.title('Phase')
        plt.axis('off')
        plt.subplot(223)
        plt.imshow(mag2, cmap=cm.Greys_r)
        plt.title('Magnitude')
        plt.axis('off')
        plt.subplot(224)
        plt.imshow(phase2, cmap=cm.Greys_r)
        plt.title('Phase')
        plt.axis('off')
        plt.savefig(filename)
Example #25
0
 def show_img(self):
     """将图像展示出来,在测试的时候很需要"""
     plt.imshow(self.__img_mat)
     plt.show()
Example #26
0
# import Dataset
from keras.datasets import mnist

## Preprosessing the Dataset

# Load Data
(x_train, y_train), (x_test, y_test) = mnist.load_data()

# parameters that describe the input data
img_x = x_train.shape[1]
img_y = x_train.shape[2]
input_shape = (img_x, img_y, 1)
num_classes = 10

# visualise data
plt.imshow(x_train[0])

# explore the dataset
print(y_train[1:10])

# convert data into a binary form
y_train = np_utils.to_categorical(y_train, 10)

# reshape data into a 4d tensor
x_train = x_train.reshape(x_train.shape[0], img_x, img_y, 1)
x_test = x_test.reshape(x_test.shape[0], img_x, img_y, 1)

# change data type
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
Example #27
0
 def showTissueMask(self):
     #plt.imshow(self.mask)
     plt.imshow(self.mask, cmap = cm.Greys_r)
     plt.show()
Example #28
0
"""

import pandas as pd
from pathlib import Path
import cv2
from matplotlib.pylab import plt
import numpy as np

if __name__ == '__main__':
    root_dir = '/Users/avelinojaver/OneDrive - Nexus365/heba/WoundHealing/raw_separate_channels/'
    root_dir = Path(root_dir)

    GT_noisy = pd.read_excel(root_dir / 'groundTruthForAvelino_30.xlsx')
    img_ids = pd.read_excel(root_dir / 'imageIDsForAvelino_30.xlsx')
    #%%
    for _, row in img_ids.iterrows():
        img_id = row['ImageNumber']
        coords = GT_noisy[GT_noisy['ImageNumber'] == img_id]

        img_path = root_dir / 'nuclei' / row['Nuclear']
        if not img_path.exists():
            continue

        img = cv2.imread(str(img_path), -1)

        xx, yy = coords['Location_Center_X'], coords['Location_Center_Y']

        plt.figure()
        plt.imshow(np.log(img + 1), 'gray')
        plt.plot(xx, yy, '.r')
Example #29
0
    for key in ('train_label', 'test_label'):
        dataset[key] = _load_label(files[key])

    if normalize:
        for key in ('train_img', 'test_img'):
            dataset[key] = dataset[key].astype(np.float32)
            dataset[key] /= 255.0

    if one_hot_label:
        for key in ('train_label', 'test_label'):
            dataset[key] = _change_one_hot_label(dataset[key])
    if not flatten:
        dataset[key] = _change_one_hot_label(dataset[key])
    return ((dataset['train_img'], dataset['train_label']),
            (dataset['test_img'], dataset['test_label']))


from matplotlib.pylab import plt

(x_train, y_train), (x_test, y_test) = load_mnist()

for i in range(10):
    img = x_train[i]
    label = np.argmax(y_train[i])
    print(label, end=", ")
    img = img.reshape(28, 28)
    plt.subplot(1, 10, i + 1)
    plt.imshow(img)
print()
plt.show()
Example #30
0
    d.r2c_plan = d.cufft.plan(
        fft_extent,
        'cufft_r2c')  #cuFFT r2c plan single precision (double = cufft_d2z)
    d.c2c_plan = d.cufft.plan(
        fft_extent,
        'cufft_c2c')  #cuFFT c2c plan single precision (double = cufft_z2z)

    d.gray = d.malloc(
        shape=gray.shape, dtype=gray.dtype, fill=gray
    )  #Allocate space for input data and set gray array as default
    d.r2c_res = d.malloc((ny, (nx // 2 + 1)),
                         'c8')  #Allocate space for r2c result
    d.r2c_full = d.malloc(gray.shape, 'c8',
                          1 + 0j)  #Allocate space for full rest
    d.c2c_res = d.malloc(gray.shape, 'c8')  #Allocate space for c2c result

    d.cufft.r2c(d.r2c_plan, d.gray, d.r2c_res)  #r2c fft
    d.cufft.add_redundants(d.r2c_plan, d.r2c_res,
                           d.r2c_full)  #Fills in the redundant values
    d.cufft.c2c(d.c2c_plan, d.r2c_full, d.c2c_res, 'cufft_inverse')  #c2c fft

    d.cublas.scal(1. / gray.size, d.c2c_res)  #Scale c2c result using cuBLAS

    result = d.c2c_res.to_host()  #Copy scaled c2c result back to host

## Using the device calls are all synchronous so the result will be ready
## by the time numpy operates on it.
fig = plt.figure()
plt.imshow(result.real)
plt.colorbar()
plt.show()
Example #31
0
text = ''
for i in range(0, len(f)):

    with open('D:\\视频\\tim专属文件\\yellow\\' + f[i], encoding='ansi') as x:
        for line in x.readlines():
            line = line.strip('\n')
            line = line.replace('<br /><br />  ', '')
            line = line.replace('<br />  ', '')
            line = line.replace(
                '<br /><br /><br /><br /><br /><br /><br /><br />', '')
            line = line.replace('<BR>  ', '')
            line = line.replace('<br /><br />', '')
            line = line.replace('<BR>', '')
            line = line.replace('nbsp', '')
            line = line.replace('br', '')
            print(0)
            text += ' '.join(jieba.cut(line))

a = Image.open('C:\\Users\\2271057973\\Pictures\\Saved Pictures\\太极.png')
mask = np.array(a)
wordcloud = WordCloud(font_path='./font/simhei.ttf',
                      background_color='white',
                      mask=mask,
                      max_font_size=120,
                      min_font_size=5).generate(text)
plt.imshow(wordcloud)
plt.axis('off')
plt.show()

wordcloud.to_file('C:\\Users\\2271057973\\Desktop\\2.png')
Example #32
0
import matplotlib
matplotlib.use('Agg')

from matplotlib.pylab import plt

from skimage.io import imread, imsave

whole_set = '2.png'
out_path = '22.png'

data = imread(whole_set)

plt.imshow(data, cmap=plt.cm.seismic)
plt.axis('off')
plt.savefig(out_path, dpi=300)