LoginSignup
16

More than 5 years have passed since last update.

画像でマスク処理をしたWordcloud作成

Last updated at Posted at 2019-02-07

はじめに

本記事では、画像でマスク処理をするワードクラウドの作成方法を紹介します。

Pythonライブラリのword_cloudのGitHubページでやっていたので前から気になってたけどやったことなかったのでやった。上手く使えば、イケてるInfographicsに使えるかも。

今回実施したこと

  • WordCloud作成
  • WordCloud作成+画像でマスク処理
  • WordCloud作成+画像でマスク処理+元画像の色を保持

インストール

Pythonライブラリword_cloudを使います。
インストールは以下のコマンドです。

コマンド
$ pip install wordcloud
or 
$ conda install -c conda-forge wordcloud

コード

以下では、関数部分のみ表示します。(全体を確認したい場合はJupyter Notebookリンクを見て下さい)

WordCloud作成

pythonスクリプト
import matplotlib.pyplot as plt
from wordcloud import WordCloud, ImageColorGenerator
import numpy as np
from PIL import Image
fpath = "C:\Windows\Fonts\meiryob.ttc" # fontは任意で

def get_wordcrowd( text ):
    wordcloud = WordCloud(background_color="black",
                          width=800,
                          height=600,
                          font_path=fpath,
                          collocations=False, # 単語の重複しないように
                         ).generate( text )

    # show
    plt.figure(figsize=(6,6), dpi=200)
    plt.imshow(wordcloud)
    plt.axis("off")
    plt.show()

get_wordcrowd(text)
ワードクラウド
image.png

WordCloud作成+画像でマスク処理

pythonスクリプト
def get_wordcrowd_mask( text, imgpath ):
    img_color = np.array(Image.open( imgpath ))
    wc = WordCloud(width=800,
                   height=600,
                   font_path=fpath,
                   mask=img_color,
                   collocations=False, # 単語の重複しないように
                  ).generate( text )

    # show
    plt.figure(figsize=(6,6), dpi=200)
    plt.imshow(wc, interpolation="bilinear")
    plt.axis("off")
    plt.show()

get_wordcrowd_mask(text, './mask_images/Keyakizaka46_logo_2.png')
マスク画像 ワードクラウド

WordCloud作成+画像でマスク処理+元画像の色を保持

pythonスクリプト
def get_wordcrowd_color_mask( text, imgpath ):
    img_color = np.array(Image.open( imgpath ))
    wc = WordCloud(width=800,
                   height=600,
                   font_path=fpath,
                   mask=img_color,
                   collocations=False, # 単語の重複しないように
                  ).generate( text )

    image_colors = ImageColorGenerator(img_color)

    # show
    plt.figure(figsize=(6,6), dpi=200)
    plt.imshow(wc.recolor(color_func=image_colors), # 元画像の色を使う
               interpolation="bilinear")
    plt.axis("off")
    plt.show()

get_wordcrowd_color_mask(text, './mask_images/Keyakizaka46_logo_2.png')
マスク画像 ワードクラウド

利用例

マスク画像 ワードクラウド
マスク画像 ワードクラウド

参考

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16