Last active
April 29, 2022 00:22
-
-
Save estshorter/011d4fc7e24d9f783cd8b1846f06524c to your computer and use it in GitHub Desktop.
identicon
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import hashlib | |
import itertools | |
from colorsys import hls_to_rgb | |
import numpy as np | |
from PIL import Image, ImageShow | |
INPUT = "1430311" | |
PIXEL = 70 # 1ピクセルのサイズ | |
MARGIN = PIXEL // 2 # 余白のサイズ | |
SIZE = PIXEL * 5 + MARGIN * 2 | |
BACKGROUND = 240 # 背景の色(0-255) | |
OPEN_IMG = True | |
def create_pattern(hash): | |
pat_half = ( | |
np.array([int(v, 16) % 2 == 0 for v in hash[:15]], dtype=np.uint8) | |
.reshape((3, 5)) | |
.T | |
) | |
pat = np.hstack([pat_half[:, -1:0:-1], pat_half]) | |
return pat | |
def create_color(hash): | |
# 0- 1 | |
hue = int(hash[-7:-4], 16) / 4095 # * 360.0 | |
lum = (75 - int(hash[-2:], 16) * 20 / 255) / 100 | |
sat = (65 - int(hash[-4:-2], 16) * 20 / 255) / 100 | |
rgb = np.array(hls_to_rgb(hue, lum, sat)) * 255 | |
return np.floor(rgb).astype(np.uint8) | |
def create_image(pattern, foreground): | |
img = np.full((SIZE, SIZE, 3), BACKGROUND, dtype=np.uint8) | |
for x, y in itertools.product(range(5), repeat=2): | |
if pattern[y, x]: | |
y_s = MARGIN + y * PIXEL | |
y_e = y_s + PIXEL | |
x_s = MARGIN + x * PIXEL | |
x_e = x_s + PIXEL | |
img[y_s:y_e, x_s:x_e] = foreground | |
return Image.fromarray(img, mode="RGB") | |
if __name__ == "__main__": | |
print(f"ID = {INPUT}") | |
hash_value = hashlib.md5(INPUT.encode()).hexdigest() | |
print(f"md5 = {hash_value}") | |
pattern = create_pattern(hash_value) | |
print(pattern) | |
foreground = create_color(hash_value) | |
print(foreground) | |
img = create_image(pattern, foreground) | |
img.save("identicon.png") | |
if OPEN_IMG: | |
ImageShow.show(img) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment