photo to char图片转字符画

最近,一个叫“图片转字符画的项目大火”,确实挺好好玩的,这次我带你们跟跟风

思路

我比较懒,不上流程图了,大致讲一下

  1. 用户输入要转换的图片路径,存储路径,存储“字符画”的规格(长、宽)
  2. 获取图片灰阶
  3. 按灰阶值选取字符
  4. 存储

实现

导入PIL.Image

from PIL import Image

获取用户输入的数据

inPath = input('path for process:')
WIDTH = int(input('How long you want for width:'))
HEIGHT = int(input('How long you want for height:'))
outPath = input('path for save:')
print('processing,please wait')

定义画中不同灰度所对应的字符

由于急着写博文,定义的字符比较少,不喜勿喷

char = u'WM%&@-.'

为了后面定义的“getchar”函数所定义的函数“limit”和数值“demarcation”

demarcation = 128
def limit(x,start,end):
   if(x <= start):
   	return start
   if(x >= end):
   	return end
   return x

获取一个rgb值的字符形式(函数“getchar”)

def getchar(r,g,b):
   gray = float(0.2126 * r + 0.7152 * g + 0.0722 * b)
   std = int(demarcation / len(char))
   return char[limit(int(gray / std),0,len(char) - 1)]

主程序

if(__name__ == '__main__'):
	img = Image.open(inPath).convert('RGB')
	img = img.resize((WIDTH,HEIGHT),Image.NEAREST)
	text = ''
	for i in range(HEIGHT):
		for j in range(WIDTH):
			r,g,b = img.getpixel((j,i))
			text += getchar(r,g,b)
		text += '\n'
	with open(outPath,'w') as file:
		file.write(text)

程序看不懂就在下方评论,应该会有人回答

测试

这里附上源代码和github链接

源代码:
from PIL import Image
inPath = input('path for process:')
WIDTH = int(input('How long you want for width:'))
HEIGHT = int(input('How long you want for height:'))
outPath = input('path for save:')
print('processing,please wait')
char = u'WM%&@-.'
demarcation = 128
def limit(x,start,end):
	if(x <= start):
		return start
	if(x >= end):
		return end
	return x
def getchar(r,g,b):
	gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b)
	std = float(demarcation / len(char))
	return char[limit(int(gray / std),0,len(char) - 1)]
if(__name__ == '__main__'):
	img = Image.open(inPath).convert('RGB')
	img = img.resize((WIDTH,HEIGHT),Image.NEAREST)
	text = ''
	for i in range(HEIGHT):
		for j in range(WIDTH):
			r,g,b = img.getpixel((j,i))
			text += getchar(r,g,b)
		text += '\n'
	with open(outPath,'w') as file:
		file.write(text)

github地址

测试

输入命令
(base) xuans-mbp:~ [马赛克] $ python main.py
path for process: a.jpg
How long you want for width: 247
How long you want for height: 101
path for save:a.txt

**原图

输出

结果
稍稍有点不太好看,但是调整“char”参数后就好多了
改char后的结果
修改:

char = u'WMBRENHFPAGKSZVXQCLUODIJTY0896543721mwqpdgbeanuskxyzfdhtocvrijl#@&$%}{][)(?=;!<>/\|-:*+~·'
demarcation = 250

参考文献

版权声明

版权归本文参考文献作者以及本人所有,转载请声明出处(懒得写就当没看见,不追究,自己知道就行)

作者

hit-road

拜拜,下课!

猜你喜欢

转载自blog.csdn.net/weixin_42954615/article/details/106645395