Visualize N-ary notation

Motivation

Wouldn't it be fun to make the N-ary notation a grayscale image? ?? ??

Implementation


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

Convert x to k-digit N-ary and output as 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)

Substitute a natural number less than or equal to k into int__n and combine


def mk_matrix(k,base):  # k:Size base:radix
    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

Convert from numpy.array to PIL.Image (imaging)


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

Image creation in 2 to 20 base


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

result

Binary base2_for_2000.png Quinary base5_for_2000.png 13-ary base13_for_2000.png 20-ary base20_for_2000.png

Impressions

Well, I knew it wasn't particularly fun. I wonder if it became a practice for PIL and numpy ...

Recommended Posts

Visualize N-ary notation
Comprehension notation
Format notation
Comprehension notation