Load TrueType Font to OpenCV

后端 未结 3 1227
长情又很酷
长情又很酷 2020-12-05 11:35

Can we load a custom TrueType font and use it with cv2.putText function ?

font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(img,\'OpenCV\',(10,500), f         


        
3条回答
  •  南笙
    南笙 (楼主)
    2020-12-05 12:00

    You can also use the library PILasOPENCV to be found at https://github.com/bunkahle/PILasOPENCV to use truetype fonts in combination with Python OpenCV. PIL or Pillow are not needed. The module depends on the library freetype-py. Fonts would be imported like this:

    from __future__ import print_function
    import PILasOPENCV as Image
    import PILasOPENCV as ImageDraw
    import PILasOPENCV as ImageFont
    import cv2
    # was: from PIL import Image, ImageDraw, ImageFont
    
    font = ImageFont.truetype("arial.ttf", 18)
    print(font)
    im = Image.open("lena.jpg")
    draw = ImageDraw.Draw(im)
    text = "Lena's image"
    draw.text((249,455), text, font=font, fill=(0, 0, 0))
    # in PIL:
    # print(font.getsize(text))
    # mask = font.getmask(text)
    print(ImageFont.getsize(text, font))
    mask = ImageFont.getmask(text, font)
    print(type(mask))
    cv2.imshow("mask", mask)
    im.show()
    

    This library is a wrapper around the common used PIL functions but works internally with OpenCV.

提交回复
热议问题