Pythonでいろいろやってみる

Pythonを使った画像処理や機械学習などの簡単なプログラムを載せています。

星を描く

pythonの画像処理ライブラリPillowを使って星を描きます 指定した位置、回転角度、頂点とへこみの直径比、色で、ImageDrawモジュールのpolygonメソッドで星を描きます

環境
  • windows10 home
  • Anaconda 3/ jupyter notebook 5.6.0
  • Python 3.7.0
  • Pillow 7.1.2
コード

(x,y)=(200,200) 、辺の長さ100,角度0°、頂点とへこみの比0.5、黄色で星を描画。

import numpy as np
from PIL import Image, ImageDraw

img_size_x = 400
img_size_y = 400

img = Image.new('RGB',(img_size_x, img_size_y), 'black')
draw = ImageDraw.Draw(img)

# 星を描画する関数 star
def star(x, y, r, theta, ratio, color):

    peak = r
    valley = r * ratio
  
    points = ()

    for i in range (0, 360, 72):
        
        angle = (theta + i) / 360 * np.pi * 2
        peak_x = int (x + peak * np.sin(angle))
        peak_y = int (y - peak * np.cos(angle))
        points += (peak_x, peak_y)
             
        angle = (theta + 36 + i) / 360 * np.pi * 2
        valley_x = int (x + valley * np.sin(angle))
        valley_y = int (y - valley * np.cos(angle))
        points += (valley_x, valley_y)     
      
    draw.polygon(points, fill=color, outline=color)

# (x,y)=(200,200) 、辺の長さ100,角度0°、頂点とへこみの比0.5、黄色で星を描画 
star(200, 200, 100, 0, 0.5,(255,255,0))

img.save('star.png')
実行結果

f:id:T_A_T:20200511092357p:plain

コード

(x,y)=(200,200) 、辺の長さ150,角度25°、頂点とへこみの比0.3、オレンジで星を描画。

import numpy as np
from PIL import Image, ImageDraw

img_size_x = 400
img_size_y = 400

img = Image.new('RGB',(img_size_x, img_size_y), 'black')
draw = ImageDraw.Draw(img)

# 星を描画する関数 star
def star(x, y, r, theta, ratio, color):

    peak = r
    valley = r * ratio
  
    points = ()
    
    for i in range (0, 360, 72):
        
        angle = (theta + i) / 360 * np.pi * 2
        peak_x = int (x + peak * np.sin(angle))
        peak_y = int (y - peak * np.cos(angle))
        points += (peak_x, peak_y)
             
        angle = (theta + 36 + i) / 360 * np.pi * 2
        valley_x = int (x + valley * np.sin(angle))
        valley_y = int (y - valley * np.cos(angle))
        points += (valley_x, valley_y)     
      
    draw.polygon(points, fill=color, outline=color)

# (x,y)=(200,200) 、辺の長さ150,角度25°、頂点とへこみの比0.3、オレンジで星を描画 
star(200, 200, 150, 25, 0.3,(255,128,128))

img.save('star.png')
実行結果

f:id:T_A_T:20200511092532p:plain

以下のサイトを参考にさせていただきました

Pythonの文法メモ > 【Pillow】ImageDrawモジュールによる直線、四角、円、多角形描画

ブログランキングに参加しています

にほんブログ村 IT技術ブログへ
にほんブログ村