转换为黑色/白色,然后转换为ASCII艺术,然后用您的文本替换ascii艺术。
PIL中的黑/白转换很容易。我得到了ASCII艺术从https://github.com/hit9/img2txt/blob/master/img2txt.py
import Image
def to_ascii(img,maxLen=100.0):
#resize to maximum line length
width, height = img.size
rate = maxLen/max(width, height)
width = int(rate * width) # cast to int
height = int(rate * height)
img_small = img.resize((width, height))
pixels = img_small.load()
string = ""
for h in xrange(height):
for w in xrange(width):
rgb = pixels[w, h]
if rgb == 0:
string += ' '
else:
string += '#'
string += "\n"
return string
def hashes_to_text(hash_art, text):
output = list(hash_art)
tidx = 0
for idx, char in enumerate(hash_art):
if char == '#':
output[idx] = text[tidx%len(text)]
tidx += 1
return ''.join(output)
这样使用它:
#open your image file and convert to black/white
image_file = Image.open('Desktop/350px-Wiktionary_small.svg.png')
image_file = image_file.convert('1') # to black/white
W = to_ascii(image_file)
W = hashes_to_text(W,'Wikipedia')
print W
将这一形象
转换成
备注:查看image segmentaion算法以改进黑/白转换。
如果您正在寻找能够实现“类似”的算法,那么您会失败,因为算法是确定性的。相反,请正式确定您的要求。 – akonsu 2015-01-21 00:46:11
一个有效的点akonsu。我想通过编程的方式实现*精确*图像中显示的内容。 – triviante 2015-01-21 01:38:31
你为什么不直接用scanline做scanline?你需要的是一个测量文本的渲染宽度的函数;一旦你有了,它或多或少是微不足道的。 – rici 2015-01-21 02:25:05