Python wordcloud.ImageColorGenerator() Examples

The following are 11 code examples of wordcloud.ImageColorGenerator(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module wordcloud , or try the search function .
Example #1
Source File: seg.py    From SentimentAnalysis with MIT License 6 votes vote down vote up
def main():
    seg = Seg()
    doc = '''自然语言处理: 是人工智能和语言学领域的分支学科。
            在这此领域中探讨如何处理及运用自然语言;自然语言认知则是指让电脑“懂”人类的语言。 
            自然语言生成系统把计算机数据转化为自然语言。自然语言理解系统把自然语言转化为计算机程序更易于处理的形式。'''
    # res = seg.seg_from_doc(doc)
    datalist = seg.get_data_from_mysql(1000, 0)
    keywords = dict(seg.get_keyword_from_datalist(datalist))

    font_path = root_path + '/data/simfang.ttf'
    bg_path = root_path + '/data/bg.jpg'
    #back_color = np.array(Image.open(bg_path))
    back_color = imread(bg_path)
    image_colors = ImageColorGenerator(back_color)
    wordcloud = WordCloud(font_path=font_path, background_color="white", mask=back_color,
                          max_words=2000, max_font_size=100, random_state=48, width=1000, height=800, margin=2)
    wordcloud.generate_from_frequencies(keywords)
    plt.figure()
    plt.imshow(wordcloud.recolor(color_func=image_colors))
    plt.axis("off")
    plt.show()
    wordcloud.to_file(root_path + '/data/pic2.png') 
Example #2
Source File: analysis.py    From web_scraping_and_data_analysis with MIT License 6 votes vote down vote up
def draw_word_cloud(content):
    d = os.path.dirname(__file__)
    img = Image.open(os.path.join(d, "changzuoren.jpg"))
    width = img.width / 80
    height = img.height / 80
    alice_coloring = np.array(img)
    my_wordcloud = WordCloud(background_color="white",
                             max_words=500, mask=alice_coloring,
                             max_font_size=200, random_state=42,
                             font_path=(os.path.join(d, "../common/font/PingFang.ttc")))
    my_wordcloud = my_wordcloud.generate_from_frequencies(content)

    image_colors = ImageColorGenerator(alice_coloring)
    plt.figure(figsize=(width, height))
    plt.imshow(my_wordcloud.recolor(color_func=image_colors))
    plt.imshow(my_wordcloud)
    plt.axis("off")
    # 通过设置subplots_adjust来控制画面外边框
    plt.subplots_adjust(bottom=.01, top=.99, left=.01, right=.99)
    plt.savefig("changzuoren_wordcloud.png")
    plt.show() 
Example #3
Source File: news_hot.py    From web_scraping_and_data_analysis with MIT License 6 votes vote down vote up
def draw_word_cloud(content):
    d = os.path.dirname(__file__)
    img = Image.open(os.path.join(d, "toutiao.jpg"))
    width = img.width / 80
    height = img.height / 80
    alice_coloring = np.array(img)
    my_wordcloud = WordCloud(background_color="white",
                             max_words=500, mask=alice_coloring,
                             max_font_size=200, random_state=42,
                             font_path=(os.path.join(d, "../common/font/PingFang.ttc")))
    my_wordcloud = my_wordcloud.generate_from_frequencies(content)

    image_colors = ImageColorGenerator(alice_coloring)
    plt.figure(figsize=(width, height))
    plt.imshow(my_wordcloud.recolor(color_func=image_colors))
    plt.imshow(my_wordcloud)
    plt.axis("off")
    # 通过设置subplots_adjust来控制画面外边框
    plt.subplots_adjust(bottom=.01, top=.99, left=.01, right=.99)
    plt.savefig("toutiao_wordcloud.png")
    plt.show() 
Example #4
Source File: stylecloud.py    From stylecloud with MIT License 5 votes vote down vote up
def gen_gradient_mask(
    size: int,
    palette: str,
    icon_dir: str = ".temp",
    gradient_dir: str = "horizontal",
    invert_mask: bool = False,
):
    """Generates a gradient color mask from a specified palette."""
    mask_array = gen_mask_array(icon_dir, invert_mask, size)
    mask_array = np.float32(mask_array)

    palette_func = gen_palette(palette)
    gradient = np.array(makeMappingArray(size, palette_func.mpl_colormap))

    # matplotlib color maps are from range of (0, 1). Convert to RGB.
    gradient *= 255.0

    # Add new axis and repeat gradient across it.
    gradient = np.tile(gradient, (size, 1, 1))

    # if vertical, transpose the gradient.
    if gradient_dir == "vertical":
        gradient = np.transpose(gradient, (1, 0, 2))

    # Turn any nonwhite pixels on the icon into the gradient colors.
    white = (255.0, 255.0, 255.0, 255.0)
    mask_array[mask_array != white] = gradient[mask_array != white]

    image_colors = ImageColorGenerator(mask_array)
    return image_colors, np.uint8(mask_array) 
Example #5
Source File: tests.py    From weibo-analysis-system with MIT License 5 votes vote down vote up
def WordCloudAPI(request):
        # ImgInfo.objects.filter(UserInfo_id=text).update(wordcloud=res)
        # print("更新完毕~~")
        # wordlist_after_jieba = jieba.cut(content, cut_all=False)
        # wl_space_split = " ".join(wordlist_after_jieba)
        # backgroud_Image = plt.imread(path.dirname(__file__) + '\color.png')
        # '''设置词云样式'''
        # stopwords = STOPWORDS.copy()
        # stopwords.add("哈哈") #可以加多个屏蔽词
        # wc = WordCloud(
        #     width=770,
        #     height=1200,
        #     background_color='white',# 设置背景颜色
        #     # mask=backgroud_Image,# 设置背景图片
        #     font_path=path.dirname(__file__) + '\simkai.ttf',  # 设置中文字体,若是有中文的话,这句代码必须添加,不然会出现方框,不出现汉字
        #     max_words=600, # 设置最大现实的字数
        #     stopwords=stopwords,# 设置停用词
        #     max_font_size=400,# 设置字体最大值
        #     random_state=50,# 设置有多少种随机生成状态,即有多少种配色方案
        # )
        # wc.generate_from_text(wl_space_split)#开始加载文本
        # img_colors = ImageColorGenerator(backgroud_Image)
        # wc.recolor(color_func=img_colors)#字体颜色为背景图片的颜色
        # d = path.dirname(__file__)
        # wc.to_file(path.join(d, "wc.jpg"))
        # print('生成词云成功!')
        # with open(path.dirname(__file__) + '\wc.jpg', 'rb') as f:
        #     base64_data = base64.b64encode(f.read())
        #     url = base64_data.decode()
        pass 
Example #6
Source File: QQZoneAnalysis.py    From QQZoneMood with MIT License 5 votes vote down vote up
def drawWordCloud(self, word_text, filename, dict_type=False, background_image='image/tom2.jpeg'):
        """

        :param word_text:
        :param filename:
        :param dict_type:
        :param background_image: 词云图的背景形状
        :return:
        """
        mask = Image.open(BASE_DIR + background_image)
        mask = np.array(mask)
        my_wordcloud = WordCloud(
            background_color='white',  # 设置背景颜色
            mask=mask,  # 设置背景图片
            max_words=2000,  # 设置最大现实的字数
            stopwords=STOPWORDS,  # 设置停用词
            font_path=self.system_font,  # 设置字体格式,如不设置显示不了中文
            max_font_size=50,  # 设置字体最大值
            random_state=30,  # 设置有多少种随机生成状态,即有多少种配色方案
            scale=1.3
        )
        if not dict_type:
            my_wordcloud = my_wordcloud.generate(word_text)
        else:
            my_wordcloud = my_wordcloud.fit_words(word_text)
        image_colors = ImageColorGenerator(mask)
        my_wordcloud.recolor(color_func=image_colors)
        # 以下代码显示图片
        plt.imshow(my_wordcloud)
        plt.axis("off")
        # 保存图片
        if not self.from_web:
            my_wordcloud.to_file(filename=self.image_path + filename + '.jpg')
            print("result file path:", self.image_path + filename + '.jpg')
            plt.show()
        else:
            my_wordcloud.to_file(filename=self.web_image_bash_path + filename + '.jpg')
            print("result file path:", self.web_image_bash_path + filename + '.jpg') 
Example #7
Source File: 歌词_6词云.py    From AI_Poet_Totoro with MIT License 5 votes vote down vote up
def show(file, pic):
    global main_dir
    d = path.dirname(__file__)
    text = open(path.join(d, main_dir+file), encoding='utf-8').read()
    # 自定义图片
    my_coloring = np.array(Image.open(path.join(d, pic)))

    # 设置停用词
    stopwords = set(STOPWORDS)
    stopwords.add("")

    # 设置词云形状
    wc = WordCloud(font_path='simhei.ttf', width=800, height= 600, background_color="white", max_words=300, mask=my_coloring,
                   stopwords=stopwords, max_font_size=110, random_state=200)
    # 运行统计
    wc.generate(text)

    # 获取color
    image_colors = ImageColorGenerator(my_coloring)

    # 展示
    plt.imshow(wc, interpolation="bilinear")
    plt.axis("off")
    plt.figure()
    wc.to_file(file+'_1.png')

    # 按照给定的图片颜色布局生成字体颜色
    plt.imshow(wc.recolor(color_func=image_colors), interpolation="bilinear")
    plt.axis("off")
    plt.figure()
    wc.to_file(file+'_2.png')

    plt.imshow(my_coloring, cmap=plt.cm.gray, interpolation="bilinear")
    plt.axis("off")
    plt.show() 
Example #8
Source File: Wc.py    From NotSoBot with MIT License 5 votes vote down vote up
def make_wc_custom(self, mask, text, max):
		try:
			coloring = np.array(PIL.Image.open(mask))
			wc = WordCloud(width=1024, height=768, max_words=max, mask=coloring)
			wc = wc.generate(' '.join(text))
			image_colors = ImageColorGenerator(coloring)
			wc = wc.recolor(color_func=image_colors)
			img = wc.to_image()
			b = BytesIO()
			img.save(b, 'png')
			b.seek(0)
			return b
		except Exception as e:
			return str(e) 
Example #9
Source File: generate_wordcloud.py    From web_scraping_and_data_analysis with MIT License 5 votes vote down vote up
def wordCloud(wordList):
    from wordcloud import WordCloud, ImageColorGenerator
    import matplotlib.pyplot as plt
    import numpy as np
    import PIL.Image as Image
    import os
    d = os.path.dirname(__file__)
    img = Image.open(os.path.join(d, "jupiter.png"))
    width = img.width/80
    height = img.height/80
    alice_coloring = np.array(img)
    my_wordcloud = WordCloud(background_color="white",
                             max_words=500, mask=alice_coloring,
                             max_font_size=200, random_state=42,
                             font_path=(os.path.join(d, "../font/PingFang.ttc")))
    my_wordcloud = my_wordcloud.generate_from_frequencies(wordList)

    image_colors = ImageColorGenerator(alice_coloring)
    plt.figure(figsize=(width, height))
    plt.imshow(my_wordcloud.recolor(color_func=image_colors))
    plt.imshow(my_wordcloud)
    plt.axis("off")
    # 通过设置subplots_adjust来控制画面外边框
    plt.subplots_adjust(bottom=.01, top=.99, left=.01, right=.99)
    plt.savefig("jupiter_wordcloud_1.png")
    plt.show() 
Example #10
Source File: create_word_cloud.py    From ChineseWordCloud with Apache License 2.0 4 votes vote down vote up
def main(input_filename):
    content = '\n'.join([line.strip()
                        for line in codecs.open(input_filename, 'r', 'utf-8')
                        if len(line.strip()) > 0])
    stopwords = set([line.strip()
                    for line in codecs.open(stopwords_filename, 'r', 'utf-8')])

    segs = jieba.cut(content)
    words = []
    for seg in segs:
        word = seg.strip().lower()
        if len(word) > 1 and word not in stopwords:
            words.append(word)

    words_df = pandas.DataFrame({'word':words})
    words_stat = words_df.groupby(by=['word'])['word'].agg({'number' : np.size})
    words_stat = words_stat.reset_index().sort_values(by="number",ascending=False)

    print '# of different words =', len(words_stat)

    input_prefix = input_filename
    if input_filename.find('.') != -1:
        input_prefix = '.'.join(input_filename.split('.')[:-1])

    for file in listdir(template_dir):
        if file[-4:] != '.png' and file[-4:] != '.jpg':
            continue
        background_picture_filename = join(template_dir, file)
        if isfile(background_picture_filename):
            prefix = file.split('.')[0]
            
            bimg=imread(background_picture_filename)
            wordcloud=WordCloud(font_path=font_filename,background_color='white',mask = bimg,max_font_size=600,random_state=100)
            wordcloud=wordcloud.fit_words(dict(words_stat.head(4000).itertuples(index=False)))

            bimgColors=ImageColorGenerator(bimg)
            wordcloud.recolor(color_func=bimgColors)

            output_filename = prefix + '_' + input_prefix + '.png'

            print 'Saving', output_filename
            wordcloud.to_file(output_filename) 
Example #11
Source File: __init__.py    From SentimentAnalysis with MIT License 4 votes vote down vote up
def main():
    doc = '''杰森我爱你!加油你是最棒的!'''
    start_time = time.time()
    datalist = Seg().get_data_from_mysql(5, 0)
    npl = SimpleNLP(1, doc, datalist)
    print(npl.seg_doc())
    print(npl.seg_datalist())

    keyword = npl.get_keyword_datalist()
    print(keyword)
    print(len(keyword))
    '''
    font_path = root_path+'/data/simfang.ttf'
    bg_path = root_path + '/data/bg.jpg'
    back_color = imread(bg_path)
    image_colors = ImageColorGenerator(back_color)
    wordcloud = WordCloud(font_path=font_path, background_color="white", mask=back_color,
                          max_words=2000, max_font_size=100, width=1000, height=800, margin=2, random_state=48)
    wordcloud.generate_from_frequencies(keyword)
    plt.figure()
    plt.imshow(wordcloud.recolor(color_func=image_colors))
    plt.axis("off")
    plt.show()
    wordcloud.to_file(root_path + '/data/pic2.png')
    
    print(npl.sentiment_analysis_doc())
    res = npl.sentiment_analysis_datalist()
    # max_qty = Counter(res).most_common(1)[0][1]
    # print(max_qty)
    print(res)
    res2 = np.array(res)
    mean = np.mean(res2)
    print(mean)

    # plt.hist(res2, bins=np.arange(0, 1, 0.005))
    # plt.title("sentiment")
    # plt.xlabel("score")
    # plt.ylabel("amount")
    # plt.show()

    end_time = time.time()
    print(end_time - start_time)

    # f = open(root_path + '/data/10w-nb-30000v2', 'w')
    # f.write(str(res))
    # f.close()
    '''