LoginSignup
11
12

More than 5 years have passed since last update.

【OpenCV】【Python】画像上に日本語のテキストを描画

Last updated at Posted at 2018-06-19

もはや、タイトルが詐欺くさい気がしないでもないです。
OpenCV単体だと大変なのでPillow(PIL)を利用しております。

日本語テキストを描画しようとしたら、パッと思いつく範囲で
以下のような対応があります(大変な順に。。。
 ・OpenCVのソースコードを修正しputTextをマルチバイト文字対応させる
 ・日本語フォントの文字画像を用意し、対象画像に重ね合わせて描画する
 ・日本語対応している他ライブラリに渡して描画する

今回はパッと表示したいだけだったので、Pillowを利用します。
ソースコードは以下。

CvPutJaText.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import cv2 as cv
import numpy as np
from PIL import ImageFont, ImageDraw, Image

class CvPutJaText:
    def __init__(self):
        pass

    @classmethod
    def puttext(cls, cv_image, text, point, font_path, font_size, color=(0,0,0)):
        font = ImageFont.truetype(font_path, font_size)

        cv_rgb_image = cv.cvtColor(cv_image, cv.COLOR_BGR2RGB)
        pil_image = Image.fromarray(cv_rgb_image)

        draw = ImageDraw.Draw(pil_image)
        draw.text(point, text, fill=color, font=font)

        cv_rgb_result_image = np.asarray(pil_image)
        cv_bgr_result_image = cv.cvtColor(cv_rgb_result_image, cv.COLOR_RGB2BGR)

        return cv_bgr_result_image

使用例は以下。
今回はフォントに「衡山毛筆フォント行書」を使用しております。

if __name__ == '__main__':
    cv_image = cv.imread("sample.jpg")

    font_path = './font/font_jb004_running_brush_wi.ttf'

    image = CvPutJaText.puttext(cv_image, u"ごんべ", (30, 30), font_path, 60, (0, 0, 0))

    cv.imshow("sample", image)
    cv.waitKey(0)

2018-06-20.png

以上。

11
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
12