python - 将大块文本转换为图像的算法? (由图像边缘定义)

标签 python c algorithm image-processing

<分区>

我有一个很大的单词列表,我希望以一种有趣的方式显示统计信息。我想打印每个单词,但在图像轮廓的边缘(用某种颜色指定)打断,这样整体上所有的文本都形成了图像。

我意识到没有例子很难理解,所以我想实现的几乎可以在 this image 中看到打印出爱丽丝梦游仙境的文字,形成书中爱丽丝和其他生物的形象; http://www.litographs.com/ 中还有很多其他示例

我想以编程方式实现上述目标,但我不确定最初从哪里开始。我开始写一个脚本来解析我的图像并只打印与透明像素所在位置对应的文本——但我很快意识到,也许我真的不想基于每个像素,而是基于边缘- 基于检测的方法会更好。我也不确定字体大小如何影响那里。

有没有我不知道的算法可以帮助我实现这一目标?我正在使用 Python/C,但我很高兴听到任何解决方案。

最佳答案

转换为黑/白,然后转换为 ascii 艺术,然后用您的文本替换 ascii 艺术。

在 PIL 中黑白转换很容易。我从 https://github.com/hit9/img2txt/blob/master/img2txt.py 得到了 ascii 艺术

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

将转换此图像

enter image description here

进入

enter image description here

备注:查看image segmentaion改进黑白转换的算法。

关于python - 将大块文本转换为图像的算法? (由图像边缘定义),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28057722/

相关文章:

python - 在特定索引之后将值添加到数据框列

c - 使用 Xcode 选项 Generate Output>Assembly 查看 C 文件的汇编代码

android - 我需要在 Android Studio 中构建 NDK。但它返回错误

c - GPU 卡在 2 秒后重置

algorithm - 负权重的 Dijkstra 算法

python - 将查询与已知列表匹配的算法,根据词典顺序呈现结果

python - 如何在 python 子列表中填写未使用的 ip 地址?

python - 在 Django 中将 REST API 放在哪里

java - 二维平面中的 K 最近邻

python - Flask-Login 中使用的 "is_authenticated"方法有什么意义?