【Python】meshgridを用いて市松模様を作成【Numpy】
2020年5月7日 2020年5月8日
PythonのNumpyのmeshgridを用いて市松模様を描いてみます!
Let’s paint “checkered pattern” by Numpy meshgrid!
こんな感じの画像を描きます。
We’ll paint such like the following.
実際のコード
実際のコードです。
Here is actual code.
import matplotlib.pyplot as plt
import numpy as np
from skimage import io
xs, ys = np.meshgrid(range(300), range(300))
canvas = np.zeros((600, 600, 3))
black_size_x, black_size_y = 60, 60
the_number_of_black_x, the_number_of_black_y = 5, 5
len_square_x, len_square_y, cnt_square_x, cnt_square_y = np.meshgrid(range(black_size_x),
range(black_size_y),
range(the_number_of_black_x),
range(the_number_of_black_y))
canvas[black_size_x + (black_size_x * 2 * cnt_square_x) + len_square_x,
black_size_y + (black_size_y * 2 * cnt_square_y) + len_square_y] = (0, 0, 1)
canvas[(black_size_x * 2 * cnt_square_x) + len_square_x,
(black_size_y * 2 * cnt_square_y) + len_square_y] = (1, 0, 0)
plt.imshow(canvas)
plt.show()
io.imsave('draw_ichimatsu1.png', canvas)
もう少し詳しく・・・ (a little more information)
まず、5行目で全体を白としたcanvasを用意します!
今回はx軸に600ピクセル、y軸に600ピクセルのキャンバスを用意しています。
そしてRGB3色分を考慮し、600×600×3のNumpy配列を値が全て0で準備するということです!
続いて、コード内の変数について説明を行います。
- black_size_x, black_size_y : x軸方向、y軸方向に対する黒色部分の長さ
the length of the black part for x-axis and y-axis - the_number_of_black_x, the_number_of_black_y : x軸方向、y軸方向に対する canvasに塗る黒色部分の数
the number of black part for x-axis and y-axis
16、17行目と18行目、19行目でどのようになっているのかわかりやすくするため16~19行目を下記のようなコードにしてみます。
I show the mechanism of line 16~19 by replacing the code like following.
#青に塗る paint with BlUE
canvas[black_size_x + (black_size_x * 2 * cnt_square_x) + len_square_x,
black_size_y + (black_size_y * 2 * cnt_square_y) + len_square_y] = (0, 0, 1)
#赤に塗る paint with RED
canvas[(black_size_x * 2 * cnt_square_x) + len_square_x,
(black_size_y * 2 * cnt_square_y) + len_square_y] = (1, 0, 0)
この時に得られる画像は次のようになります!
公式サイト等のmeshgridに関する説明と照らし合わせてなぜこうなるか理解してみてください!