1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

N進法を可視化する

Posted at

#動機
N進法をグレースケールの画像にしたら楽しいのでは???

#実装


import numpy as np
import math
from tqdm import tqdm
from PIL import Image

xをk桁のN進数に変換してnumpy.arrayで出力
(ex. x=10,n=2,k=8 → 00001010)


def int__n(x,n,k):
    if x>(n**k-1):
#       print("x over maximum\n","x=",x," n**k-1=",n**k-1)
#       print("n=",n," k=",k)
        return np.full(k,n-1)
    else:
        a = x%(n**(k-1))
        b = x//(n**(k-1))
        if k==1:
            return np.array([b])
        else:
            v = int__n(a,n,k-1)
            return np.insert(v,0,b,axis=0)

k以下の自然数をint__nに代入して結合


def mk_matrix(k,base):  # k:サイズ base:基数
    c = int(math.log(k,base)+2)
    m = np.full((0,c),0)
    for i in range(k):
        v = int__n(i+1,base,c)
        m = np.insert(m,i,v,axis=0)
    return m

numpy.arrayからPIL.Imageに変換(画像化)


def mk_img(x,base):
    M = np.uint8((255/(base-1)*((base-1)-mk_matrix(x,base))))
#   Image.fromarray(M).convert("L").resize((x,x)).show()
    img = Image.fromarray(M).convert("L").resize((x,x))
    img.save("base{base}_for_{x}.png".format(base=base,x=x))
    img.resize((500,500)).save("base{base}_for_{x}_resized_500x500.png".format(base=base,x=x))

2~20進法で画像作成


for n in tqdm(range(2,21)):
    mk_img(2000,n)

#結果
2進法
base2_for_2000.png
5進法
base5_for_2000.png
13進法
base13_for_2000.png
20進法
base20_for_2000.png

#感想
まあ、特に楽しいことはないですね、わかってはいましたが。
PILとnumpyの練習にはなったかな…

1
1
0

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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?