ドナルド

【返金可】Pythonでおしゃれで可愛い画像を作る🐱

プラグラミングを学んでいて、「何か面白い事したいなー」と思ってるそこのアナタ。

Pythonを学びながら、こんな可愛くてこシャレオツな画像作ってみたいなー、なんて思いませんか?

画像33

Python使えば、自分好みにサクッと作れちゃいます。

こんな方におすすめです。

・Pythonを学習し始めて、基礎的なことは理解して、何か面白いことできないかな〜と悩んでいる方。
Pythonのレベルをもっとあげたい方
遊びながら、Pythonを学びたい方。

こんな方にはおすすめじゃありません。

・ProgateのPython初級コースを、まだされた事ないようなビギナーの方。
・反対に、下記のgithubを見て、余裕で理解できるくらいのPythonリテラシーがおありの方。

目次

①このnoteで出来るようになる事
②おすすめの環境
③では、やっていきましょう!

①このnoteで出来るようになる事

このような画像が、簡単に作れるようになります。

画像3

画像4

画像5

画像6

画像7

②おすすめの環境

環境はなんでも問題ありませんが、おすすめは「Jupyter Notebook」です。

今回が初トライな方は、以下の流れで環境を作っちゃいましょう。
※本noteは、「Jupyter notebook」での使用を前提にしております。

「Anaconda」をインストールして、
②「Jupyter notebook」を立ち上げます

とても簡単ですが、
迷ったときはこちらの記事がわかりやすいので、ご覧ください。
・データ分析で欠かせない!Jupyter Notebookの使い方【初心者向け】
・【Python】Jupyter notebookの基本的な使い方を分かりやすく説明する

③では、やっていきましょう!

ここからの流れです。

③-1:必要なライブラリをインストールして、インポート
③-2:表示される単語の元になる、テキストを取り込む
③-3:ワードクラウドを作る
③-4:型どりたい画像を探して、取り込む
③-5:その形にワードクラウドを作ってくれ!ってコマンド入れるだけ
③-6:さらにシャレオツに✌️

Here we go!🏎💨💨💨

③-1:必要なライブラリをインストールして、インポート

Anacondaから、ターミナル(所謂、黒い画面)を立ち上げあげて、「wordcloud」をインストールします。

画像8

pip install wordcloud

「Jupyter notebook」を立ち上げて、今回使うライブラリをimportしましょう。↓をそのままコピペすればOKです。

#ワードクラウド用ライブラリ
from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator

#画像を加工するのに関係するライブラリ
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt

#その他で使用するライブラリ
from os import path
import os


③-2:表示される単語の元になる、テキストを取り込む

単語の元になる英語のテキストを取り込んでみます。

何でも良いのですが、ここでは、

アフリカ系アメリカ人公民権運動の指導者として活動した「マーティン・ルーサー・キング・ジュニア(通称、キング牧師)」の名スピーチ

「I Have a Dream」の原文を使ってみましょう。

画像9

こちらのサイトからスピーチの全文ドラッグしてコピペするか、↓をそのままコピペ。

dream = "I am happy to join with you today in what will go down in history as the greatest demonstration for freedom in the history of our nation.Five score years ago, a great American, in whose symbolic shadow we stand today, signed the Emancipation Proclamation. This momentous decree came as a great beacon light of hope to millions of Negro slaves who had been seared in the flames of withering injustice. It came as a joyous daybreak to end the long night of their captivity.But one hundred years later, the Negro still is not free. One hundred years later, the life of the Negro is still sadly crippled by the manacles of segregation and the chains of discrimination. One hundred years later, the Negro lives on a lonely island of poverty in the midst of a vast ocean of material prosperity. One hundred years later, the Negro is still languishing in the corners of American society and finds himself an exile in his own land. So we have come here today to dramatize a shameful condition.In a sense we have come to our nation’s capital to cash a check. When the architects of our republic wrote the magnificent words of the Constitution and the Declaration of Independence, they were signing a promissory note to which every American was to fall heir. This note was a promise that all men, yes, black men as well as white men, would be guaranteed the unalienable rights of life, liberty, and the pursuit of happiness.It is obvious today that America has defaulted on this promissory note insofar as her citizens of color are concerned. Instead of honoring this sacred obligation, America has given the Negro people a bad check, a check which has come back marked “insufficient funds.” But we refuse to believe that the bank of justice is bankrupt. We refuse to believe that there are insufficient funds in the great vaults of opportunity of this nation. So we have come to cash this check — a check that will give us upon demand the riches of freedom and the security of justice. We have also come to this hallowed spot to remind America of the fierce urgency of now. This is no time to engage in the luxury of cooling off or to take the tranquilizing drug of gradualism. Now is the time to make real the promises of democracy. Now is the time to rise from the dark and desolate valley of segregation to the sunlit path of racial justice. Now is the time to lift our nation from the quick sands of racial injustice to the solid rock of brotherhood. Now is the time to make justice a reality for all of God’s children.It would be fatal for the nation to overlook the urgency of the moment. This sweltering summer of the Negro’s legitimate discontent will not pass until there is an invigorating autumn of freedom and equality. Nineteen sixty-three is not an end, but a beginning. Those who hope that the Negro needed to blow off steam and will now be content will have a rude awakening if the nation returns to business as usual. There will be neither rest nor tranquility in America until the Negro is granted his citizenship rights. The whirlwinds of revolt will continue to shake the foundations of our nation until the bright day of justice emerges.But there is something that I must say to my people who stand on the warm threshold which leads into the palace of justice. In the process of gaining our rightful place we must not be guilty of wrongful deeds. Let us not seek to satisfy our thirst for freedom by drinking from the cup of bitterness and hatred.We must forever conduct our struggle on the high plane of dignity and discipline. We must not allow our creative protest to degenerate into physical violence. Again and again we must rise to the majestic heights of meeting physical force with soul force. The marvelous new militancy which has engulfed the Negro community must not lead us to a distrust of all white people, for many of our white brothers, as evidenced by their presence here today, have come to realize that their destiny is tied up with our destiny. They have come to realize that their freedom is inextricably bound to our freedom. We cannot walk alone.As we walk, we must make the pledge that we shall always march ahead. We cannot turn back. There are those who are asking the devotees of civil rights, “When will you be satisfied?” We can never be satisfied as long as the Negro is the victim of the unspeakable horrors of police brutality. We can never be satisfied, as long as our bodies, heavy with the fatigue of travel, cannot gain lodging in the motels of the highways and the hotels of the cities. We cannot be satisfied as long as the Negro’s basic mobility is from a smaller ghetto to a larger one. We can never be satisfied as long as our children are stripped of their selfhood and robbed of their dignity by signs stating “For Whites Only”. We cannot be satisfied as long as a Negro in Mississippi cannot vote and a Negro in New York believes he has nothing for which to vote. No, no, we are not satisfied, and we will not be satisfied until justice rolls down like waters and righteousness like a mighty stream.I am not unmindful that some of you have come here out of great trials and tribulations. Some of you have come fresh from narrow jail cells. Some of you have come from areas where your quest for freedom left you battered by the storms of persecution and staggered by the winds of police brutality. You have been the veterans of creative suffering. Continue to work with the faith that unearned suffering is redemptive.Go back to Mississippi, go back to Alabama, go back to South Carolina, go back to Georgia, go back to Louisiana, go back to the slums and ghettos of our northern cities, knowing that somehow this situation can and will be changed. Let us not wallow in the valley of despair.I say to you today, my friends, so even though we face the difficulties of today and tomorrow, I still have a dream. It is a dream deeply rooted in the American dream.I have a dream that one day this nation will rise up and live out the true meaning of its creed: “We hold these truths to be self-evident: that all men are created equal.”I have a dream that one day on the red hills of Georgia the sons of former slaves and the sons of former slave owners will be able to sit down together at the table of brotherhood.I have a dream that one day even the state of Mississippi, a state sweltering with the heat of injustice, sweltering with the heat of oppression, will be transformed into an oasis of freedom and justice.I have a dream that my four little children will one day live in a nation where they will not be judged by the color of their skin but by the content of their character.I have a dream today.I have a dream that one day, down in Alabama, with its vicious racists, with its governor having his lips dripping with the words of interposition and nullification; one day right there in Alabama, little black boys and black girls will be able to join hands with little white boys and white girls as sisters and brothers.I have a dream today.I have a dream that one day every valley shall be exalted, every hill and mountain shall be made low, the rough places will be made plain, and the crooked places will be made straight, and the glory of the Lord shall be revealed, and all flesh shall see it together.This is our hope. This is the faith that I go back to the South with. With this faith we will be able to hew out of the mountain of despair a stone of hope. With this faith we will be able to transform the jangling discords of our nation into a beautiful symphony of brotherhood. With this faith we will be able to work together, to pray together, to struggle together, to go to jail together, to stand up for freedom together, knowing that we will be free one day.This will be the day when all of God’s children will be able to sing with a new meaning, “My country, ‘tis of thee, sweet land of liberty, of thee I sing. Land where my fathers died, land of the pilgrim’s pride, from every mountainside, let freedom ring.”And if America is to be a great nation this must become true. So let freedom ring from the prodigious hilltops of New Hampshire. Let freedom ring from the mighty mountains of New York. Let freedom ring from the heightening Alleghenies of Pennsylvania!Let freedom ring from the snowcapped Rockies of Colorado!Let freedom ring from the curvaceous slopes of California!But not only that; let freedom ring from Stone Mountain of Georgia!Let freedom ring from Lookout Mountain of Tennessee!Let freedom ring from every hill and molehill of Mississippi. From every mountainside, let freedom ring."

こんな感じになったらOKです。
画像10

※「英語のそれっぽいテキスト」であれば何でも大丈夫です。お好みで遊んでみてください。


③-3:ワードクラウドを作る

まず、(Macの方は)表示させる際のフォントを指定する必要があるので、
フォントの在りかまでのパスを指定おきます。

#フォントまでのパス
fpath = "/Library/Fonts/Chalkboard.ttc"

ここでは、試しに「Chalkboard.ttc」というフォントを指定しています。

Chalkboard.ttc

画像11

※ここのパスの最後の指定を変える事(ファイル名をそのまま入れる)で、いろんなフォントで作ることができます。慣れてきたら遊んでみてください

画像12


早速作ってみましょう。↓をそのまま実行してみてください。

#まず、通常のワードクラウドを作ってみる
wordcloud = WordCloud(
    background_color="white", #背景色を指定します。
    font_path=fpath, #Macの場合、フォントまでのパスをしているする必要がある
    stopwords = STOPWORDS, #表示させない用語リストを用意する。STOPWORDSがあらかじめ使える
    width=900, #横幅
    height=500, #縦幅
).generate(dream) #ここに、テキストデータを入れた変数を入れます

これで、ワードクラウドができました(簡単)。
早速表示させてみましょう!

#作ったワードクラウドを表示する
plt.figure(figsize=(12,10)) #表示サイズを指定する
plt.imshow(wordcloud) #表示させるワードクラウドの変数を入れる
plt.title("I Have a Dream") #画像タイトル。非表示も可能
plt.axis("off") #グリッド線のon/off
plt.show()

こんな感じに表示されたら成功です😄

画像13

どうでしょう?この段階でも結構シャレオツじゃないですか?。Tシャツにしたいですね。

でも、ここからがもっと面白くなります。


③-4:型どりたい画像を探して、取り込む

今だと、長方形なので、もっとシャレオツにしたいですよね。

ワードクラウドを型どりたい画像を用意します。

画像は、背景が透明である必要があります。
↓のサイトをご参考にお好きな画像を探してみると楽しいです。

知らないと損する透過画像のみに絞ってGoogle画像で検索する方法でやる
Pinterestを使って探す


ここでは、①の方法で探したこのキング牧師の画像を使ってみます。
この画像を、「martin-luther-king.png」というファイル名で、保存します。

画像14

保存し終わったら、下記を実行してみてください。

#画像を取り込む準備
d = path.dirname(__file__) if "__file__" in locals() else os.getcwd()

#king_imageという変数に取り込みます
king_image = np.array(Image.open(path.join(d, "martin-luther-king.png"))) #ここに画像のファイル名を入れます

画像15

詳しい説明は割愛しますが、取り込んだ画像をnumpyで数値データに変換してます。


(ここは、読み飛ばしても問題ありません)ついでに、表示させたくない単語が表示しないように除外リストに追加してみましょう

画像16

先ほど作ったワードクラウドをみてみると、
Negro(黒人)と言った少々差別用語チックな単語や、will, comeなどのこれといってシャレオツじゃない単語がデカデカ表示されてます。

もっと、イイカンジにしたいですよね。

これらの単語が表示されないように、表示禁止リストに追加します。
STOPWORDSというあらかじめ用意された表示禁止リストに追加します。

#表示させないキーワードを追加する
add_STOPWORDS = ["Negro","will","come"]

#addで一つずつ追加するを繰り返す
for i in add_STOPWORDS:
    STOPWORDS.add(i)
    
    
str(STOPWORDS)

画像17


③-5:その形にワードクラウドを作ってくれ!ってコマンド入れるだけ

準備が整いました。

maskという引数に画像を取り込んだ変数をセットします。
※wordcloud_2に、変数名を変えてます

#ワードクラウドを作る。wordcloud_2
wordcloud_2 = WordCloud(
    background_color="white", #背景色
    font_path=fpath, #Macの場合、フォントまでのパスをしているする必要がある
    stopwords = STOPWORDS, #ワードクラウドに含まない用語リストを用意する。STOPWORDSがあらかじめ使える
    width=900, #横幅
    height=500, #縦幅
    mask=king_image #maskという引数に、先ほど取り込んだ画像を入れた変数を入れます
).generate(str(dream))

表示させてみましょう。

#作ったワードクラウドを表示する
plt.figure(figsize=(12,10)) #表示サイズを指定する
plt.imshow(wordcloud_2) #表示させるワードクラウドの変数を入れる
#plt.title("title") #画像タイトル。非表示も可能
plt.axis("off") #グリッド線のon/off
plt.show()

画像18

こんな感じに出力されたら成功。元の画像の形になっててイイ感じです。

画像19

また、Negro、will、comeの単語は消えてますね。
dreamやnation(国家)が真ん中にデカデカときてます。

シャレオツじゃないですか?シャレオツですよね。

はい、シャレオツです。


③-6:さらにシャレオツに✌️

おなじみ、ミッ●ーとドナ●ドです。
このように、画像の場所によって、単語の色が変わるようにできます。

画像20

画像21

とてもシャレオツです。
作った方、最高にセンスあると思います。

これも、サクッと作れてしまいます。

ちなみに元の画像はこちらです🍰


ここから先は

3,159字 / 13画像
この記事のみ ¥ 150
期間限定 PayPay支払いすると抽選でお得に!

貴重なお時間で読んでいただいてありがとうございます。 感謝の気持ちで、いっPython💕