Last active
March 27, 2021 11:20
-
-
Save jdhao/71cf8429299df3dbb0d640d0b91310ee to your computer and use it in GitHub Desktop.
Draw text on image using PIL or OpenCV. Two complete examples are given.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import cv2 | |
img = cv2.imread("test.jpg") | |
# OpenCV only support limited font and can only | |
# draw ASCII characters. If you want to draw non-ASCII | |
# characters on image, better use PIL | |
font = cv2.FONT_HERSHEY_PLAIN | |
# color is in BGR format, so the first component is B, second | |
# component is G, and the third component is for R. | |
# Do not get it wrong | |
color = (0, 0, 255) | |
# (x, y) are the coordinates where you want to draw text. | |
# The doc on `putText` is https://goo.gl/sEqDSf | |
# putText only support ascci characters, all other characters are rendered as box | |
cv2.putText(img, text="some text", org=(x, y), | |
fontFace=font, fontScale=1, color=color, thickness=1) | |
cv2.imshow("image", img) | |
cv2.waitKey(0) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from PIL import Image, ImageFont, ImageDraw | |
im = Image.new('RGB', (1024, 1024), (255, 255, 255)) | |
# in the font parameter, use a valid path to a font | |
font = ImageFont.truetype( | |
font="D:/code_exprt/fzyh.ttf", | |
size=250) | |
drawer = ImageDraw.Draw(im) | |
# we can measure the size of text in pixel with `textsize()` method | |
text_size = drawer.textsize(text="大美中國", font=font) | |
print("text size is {}".format(text_size)) | |
# draw text on image with specified font and color, | |
# the doc on ImageDraw.text is https://goo.gl/m7hKcc | |
drawer.text((10, 10), "大美中國", font=font, fill=(10, 10, 10)) | |
im.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
approved.