【问题标题】:Writing Japanese texts on images using PIL package使用 PIL 包在图像上编写日语文本
【发布时间】:2021-06-22 06:10:48
【问题描述】:

我有一个日语单词数据集,我想使用 PIL 包在图像(黑色背景和白色文字的图像)上绘制它们。

这是我的部分代码:

# -*- coding: utf-8 -*-

from PIL import Image, ImageDraw, ImageFont
import textwrap
import numpy as np
import sys
import os
import re

def draw_my_text(txt):
    para = textwrap.wrap(txt, width = 23) #change width maybe
    img = Image.new("L", (width, height), color=0)   # "L": (8-bit pixels, black and white)
    font = ImageFont.truetype("./data/arial.ttf", font_size)
    draw = ImageDraw.Draw(img)
    
    cur_h, pad = 200, 10
    for line in para:
        w, h = draw.textsize(line, font=font)
        draw.text(((width - w)/2, cur_h), line, fill='white', font=font)
        cur_h += h + pad
        
    image_name = "img_" + str(counter)
    img.save('./' + folder_name + "/"+ test_f_name + "/" + image_name + '.png')
    f1.write(txt + os.linesep)
    f2.write("word" + os.linesep)


with open('./' + folder_name + '/list_of_labels_test_type_20210622.txt', 'w') as f2:
    with open ('./' + folder_name + '/list_of_labels_test_20210622.txt', 'w') as f1:
        for sentence in all_sentences:
            text = sentence
            img = Image.new("L", (width, height), color=0)   # "L": (8-bit pixels, black and white)
            font = ImageFont.truetype("./data/arial.ttf", font_size)
            draw = ImageDraw.Draw(img)
            w, h = draw.textsize(text, font=font)
            #print(w)
            if w > 950:
                ls = len(text)
                list_of_returned_spaces = findSpacePosition(text)
                #text = text_to_splittedText(text, list_of_returned_spaces)
                #fixme
            for j in range(n_stim_repetition):
                counter = draw_sentence(text, width, height, counter, font, font_size)
                f1.write(sentence[:-1] + os.linesep)
                f2.write("sentence" + os.linesep)
                counter = draw_words_of_sentence(text, width, height, counter, font, font_size) 
                counter = draw_sentence(text, width, height, counter, font, font_size)
                f1.write(sentence[:-1] + os.linesep)
                f2.write("sentence" + os.linesep)
                counter = draw_rest_blank(width, height, counter)
                f1.write("........" + os.linesep)
                f2.write("rest" + os.linesep)

函数draw_(something),都调用了

draw_my_text(txt)

用于将文本绘制到图像。我已经用这些代码来画英文单词了,效果很好。

但是,当我使用日语时,只绘制了一些正方形

我的文本文件如下所示:

我应该如何更改我的代码来解决这个问题?

【问题讨论】:

    标签: python text python-imaging-library drawing special-characters


    【解决方案1】:

    我下载的不是“arial”字体,而是 MSMINCHO.TTF 字体(主要用于日语),现在一切正常。

    【讨论】:

      猜你喜欢
      • 2019-11-07
      • 2019-01-17
      • 2013-04-28
      • 1970-01-01
      • 2017-08-10
      • 2021-04-04
      • 2011-12-03
      • 2012-03-05
      • 2021-08-23
      相关资源
      最近更新 更多