python利用图片拼凑汉字
作者:互联网
文章目录
前言
在拼了照片墙之后,发现一个更好玩的需求,就是用图片拼凑汉字,这样就可以写一句自己想写的话。与照片墙不一样的就是,汉字对应的点阵比较难处理,这里借鉴了其他网友的智慧。
准备汉字图片
这段代码来自这篇博客https://blog.csdn.net/johinieli/article/details/76151247
import os
import pygame
chinese_dir = 'font_pic'
if not os.path.exists(chinese_dir):
os.mkdir(chinese_dir)
pygame.init()
start,end = (0x4E00, 0x9FA5) # 汉字编码范围
for codepoint in range(int(start), int(end)):
word = chr(codepoint)
font = pygame.font.Font("C:\Windows\Fonts\STFANGSO.TTF", 64) # 没有字体的话需要相应修改
# 64是生成汉字的字体大小
rtext = font.render(word, True, (0, 0, 0), (255, 255, 255))
pygame.image.save(rtext, os.path.join(chinese_dir, word + ".png"))
运行完之后在自己相应的文件夹内会生成汉字图片
获得汉字点阵
直接读取图片转为灰度图然后二值化即可。
img = Image.open("./font_pic/一.png").convert("L")
img.thumbnail((20, 26))
print(img.size)
matrix = np.array(img)
flag = (matrix < 255) + 0
print(flag)
可以看到汉字一被二值化的结果
绘制汉字
以上都只是一些铺垫,真正绘制的代码在这,如果不明白建议先去看一看我的另一篇博客https://blog.csdn.net/weixin_44112790/article/details/100171105,搞清楚照片墙怎么绘制的。
import os
import numpy as np
from PIL import Image
titles = os.listdir("./pics") # 获得所有图片的文件名列表
def draw_hanzi(matrix, each_width=192, each_height=108, save_name=""):
N = matrix.shape[0]
M = matrix.shape[1]
image = Image.new("RGB", (each_width*M, each_height*N)) # 准备空画布
# 记录坐标
x = 0
y = 0
# 循环画图
for i in range(0, N*M):
if matrix[y][x] == 1:
img = Image.open("./pics/"+titles[i % len(titles)])
img = img.resize((each_width, each_height)) # 调整尺寸
image.paste(img, (x*each_width, y*each_height)) # 粘贴到指定位置
x += 1
if x == M: # 满一行重置x,y+=1
x = 0
y += 1
# image.show()
image.save("./res/"+save_name)
if __name__ == '__main__':
img = Image.open("./font_pic/爱.png").convert("L")
img.thumbnail((40, 60))
print(img.size)
matrix = np.array(img)
flag = (matrix < 255) + 0
print(flag)
draw_hanzi(flag, save_name="爱.png")
最终得到的结果如下
标签:matrix,img,拼凑,python,汉字,each,font,os 来源: https://blog.csdn.net/weixin_44112790/article/details/100595912