我想读取一个文本文件并从其中提取德语文本,并使用PIL和python2.7将其写入png图像,但是当使用.text()写入图像时,每当出现某个外文字符时,我都会得到未知的文本。我用过arialunicodems.ttf作为字体。
首先,我使用Microsoft认知视觉从图像中提取文本,并对每个单词使用.encode(utf-8),并结合单词在英语中生成一个句子,然后使用python翻译库将文本转换为德语。然后使用arialunicodems.ttf作为字体,并使用PIL的.text()函数在png上绘制文本。它是为德文、中文、印地语等正确绘制的,但后来我想添加一个功能,以便用户能够更改翻译的文本,如果翻译不正确的话。为此,我将原始文本和翻译后的文本保存在.txt文件中,并将txt文件的内容显示给用户,用户在需要时对其进行更改,更改后的文本再次保存到txt文件中。然后使用另一个python程序,我将文本添加到图像中。但是,这一次,无论何时,文本都是胡言乱语,它会在图像上绘制☐。对印地语来说,这完全是胡说八道。有什么问题吗?
工作代码:我把单词连在一起形成一个句子的一部分(用可变文本保存)。
for word in word_infos:
bbox = [int(num) for num in word["boundingBox"].split(",")]
if bbox[0]>=x and bbox[1]>=y and bbox[0]+bbox[2]<=x+w and bbox[1]+bbox[3]<=y+h:
text = text+word["text"].encode('utf-8')+" "
我把文字写成图像的部分
im = Image.open("check.png")
d = ImageDraw.Draw(im)
helvetica = ImageFont.truetype("arialunicodems.ttf",10)
d.text((x,y), mtranslate.translate(text, sys.argv[3], sys.argv[2]), font=helvetica, fill=(0,0,0))
不工作代码:将提取的文本保存到txt文件的部分
for word in word_infos:
bbox = [int(num) for num in word["boundingBox"].split(",")]
if bbox[0]>=x and bbox[1]>=y and bbox[0]+bbox[2]<=x+w and bbox[1]+bbox[3]<=y+h:
text = text+word["text"].encode('utf-8')+" "
file.write("orignaltext:"+text+"\n")
从txt文件中提取文本并在图像上写入的部分
im = Image.open("check.png")
d = ImageDraw.Draw(im)
file2 = open("1.txt","r")
printframe = file2.readlines()
#j and traceorig is defined to extract text in loop
orig = printframe[j*6+3][traceorig:len(printframe[j*6+3])-1].encode('utf-8')
#xstr,ystr,r,g,b are extracted from image
d.text((int(xstr),int(ystr)), mtranslate.translate(orig,"de","en").encode('utf-8'), font=helvetica, fill=(int(r), int(g), int(b)))
关于英文的“概述”,我想
德文:于布利克
印地语:अवलोकन
在更新的代码中,当我在终端上打印时,它会正确地打印,但是在它所写的图像上。
德文:☐berblick
印地语:找不到字符,请看图片链接印地语翻译图像。
更新1:
生成类似结果的示例代码
#!/usr/bin/python
# -*- coding: utf-8 -*-
from PIL import Image, ImageDraw, ImageFont, ImageFilter
import cv2
import numpy as np
import sys
import os
reload(sys)
sys.setdefaultencoding('utf8')
#file has only one line with text "Überblick"
file1 = open("write.txt","w+")
file1.write("Überblick")
file1.close()
file2 = open("write.txt","r")
content = file2.readlines()
file2.close()
img = np.zeros((300,300,1), np.uint8)
cv2.imwrite("stack.png",img)
im = Image.open("stack.png")
d = ImageDraw.Draw(im)
helvetica = ImageFont.truetype("arialunicodems.ttf",50)
d.text((0,100), content[0].encode('utf-8'), font=helvetica, fill="white")
im.save("processed.png")
os.remove("stack.png")
有关输出,请参见processed.png。arialunicodems.ttf文件
发布于 2019-06-27 14:42:34
所以我自己想出来了。任何在使用Python2.x和PIL在图像上写入unicode文本有问题的人,请先阅读此链接。它提供了关于不同版本python中文本编码的非常丰富的信息。答案是使用unicode()。删除.encode('utf-8')并使其类似于:
d.text((0,100), unicode(content[0]), font=helvetica, fill="white")
unicode()是将任何字符串转换为unicode字符串,类似于str()转换为字符串。希望这能帮助有需要的人。
https://stackoverflow.com/questions/56749838
复制相似问题