我们可以加载自定义TrueType字体并将其与cv2.putText
函数一起使用吗?
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(img,'OpenCV',(10,500), font, 4,(255,255,255),2,cv2.LINE_AA)
答案 0 :(得分:7)
在OpenCV中,只支持Hershey字体的一部分。
在opencv2/core.hpp
中,您可以找到此枚举HersheyFonts。
//! Only a subset of Hershey fonts
enum HersheyFonts {
FONT_HERSHEY_SIMPLEX = 0, //!< normal size sans-serif font
FONT_HERSHEY_PLAIN = 1, //!< small size sans-serif font
FONT_HERSHEY_DUPLEX = 2, //!< normal size sans-serif font (more complex than FONT_HERSHEY_SIMPLEX)
FONT_HERSHEY_COMPLEX = 3, //!< normal size serif font
FONT_HERSHEY_TRIPLEX = 4, //!< normal size serif font (more complex than FONT_HERSHEY_COMPLEX)
FONT_HERSHEY_COMPLEX_SMALL = 5, //!< smaller version of FONT_HERSHEY_COMPLEX
FONT_HERSHEY_SCRIPT_SIMPLEX = 6, //!< hand-writing style font
FONT_HERSHEY_SCRIPT_COMPLEX = 7, //!< more complex variant of FONT_HERSHEY_SCRIPT_SIMPLEX
FONT_ITALIC = 16 //!< flag for italic font
};
如果要使用自定义字体,可以尝试PIL.ImageFont。
此处提供了一个基本示例:
import numpy as np
from PIL import ImageFont, ImageDraw, Image
import cv2
import time
## Make canvas and set the color
img = np.zeros((200,400,3),np.uint8)
b,g,r,a = 0,255,0,0
## Use cv2.FONT_HERSHEY_XXX to write English.
text = time.strftime("%Y/%m/%d %H:%M:%S %Z", time.localtime())
cv2.putText(img, text, (50,50), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (b,g,r), 1, cv2.LINE_AA)
## Use simsum.ttc to write Chinese.
fontpath = "./simsun.ttc"
font = ImageFont.truetype(fontpath, 32)
img_pil = Image.fromarray(img)
draw = ImageDraw.Draw(img_pil)
draw.text((50, 100), "国庆节/中秋节 快乐!", font = font, fill = (b, g, r, a))
img = np.array(img_pil)
## Display
cv2.imshow("res", img);cv2.waitKey();cv2.destroyAllWindows()
cv2.imwrite("res.png", img)
答案 1 :(得分:5)
对于新查看者,OpenCV自OpenCV 3.0.0起通过FreeType2类支持自定义字体。参见一些不错的示例代码:https://docs.opencv.org/4.1.1/d9/dfa/classcv_1_1freetype_1_1FreeType2.html
答案 2 :(得分:0)
您还可以使用https://github.com/bunkahle/PILasOPENCV处的库PILasOPENCV将truetype字体与Python OpenCV结合使用。不需要PIL或枕头。该模块取决于库freetype-py。字体将这样导入:
iris %>%
group_by(Species) %>%
summarise(out = list(SlowFunction(Sepal.Length))) %>%
unnest
# A tibble: 3 x 3
# Species mean sd
# <fct> <dbl> <dbl>
#1 setosa 5.01 0.352
#2 versicolor 5.94 0.516
#3 virginica 6.59 0.636
该库是常用PIL函数的包装,但在内部与OpenCV一起使用。