本文受 如何让 DeepSeek 画画 启发。
项目已经开源在 Github 上了,本文中的代码将不再更新,如果有 Bug 请在 Github 上发 issue。
原理
显然我们可以对图片进行分块,在每一块中随机取 个点,将它们的颜色的平均值作为这一块的颜色。这也是马赛克的原理。
实现
然后我们从上面那篇文章中学习到了如何用 画画,所以我就有了这样一个想法:输入一张图片,输出它所对应的像素版本的 :
pic2tex.py
import cv2
import math
import random
import sys
import numpy as np
img=cv2.imdecode(np.fromfile(sys.argv[1], dtype=np.uint8), cv2.IMREAD_COLOR)
height=(img.shape)[0]
width=(img.shape)[1]
size=int(sys.argv[2])
print(r"\newcommand{\px}[1]{\color{#1}{\rule{5pt}{5pt}}}")
k=30
for i in range(0, height, math.ceil(height/size)):
for j in range(0, width, math.ceil(width/size)):
r, g, b=0, 0, 0
for _ in range(0, k):
randi=min(i+random.randint(0, math.ceil(height/size)-1), height-1)
randj=min(j+random.randint(0, math.ceil(width/size)-1), width-1)
z, y, x=img[randi, randj]
r+=x/k
g+=y/k
b+=z/k
r=math.floor(r)
g=math.floor(g)
b=math.floor(b)
col='{:02X}{:02X}{:02X}'.format(r, g, b)
print("\\px{"+col.lower()+"}", end="")
if i+math.ceil(height/size)<height:
print("\\\\[-7pt]")使用方法是在命令行中输入 python pic2tex.py <图片文件> <生成图片尺寸>。
记得下载 python、cv2、numpy。
你可以调整 来产生一些不同的效果。
