cv_puttext.py 808 B

12345678910111213141516171819202122
  1. import cv2
  2. import numpy as np
  3. from PIL import Image, ImageDraw, ImageFont
  4. def cv2ImgAddText(img, text, left, top, textColor=(0, 255, 0), textSize=20):
  5. if (isinstance(img, np.ndarray)): #判断是否OpenCV图片类型
  6. img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
  7. draw = ImageDraw.Draw(img)
  8. fontText = ImageFont.truetype(
  9. r"C:\Windows\Fonts\simhei.ttf", textSize, encoding="utf-8")
  10. draw.text((left, top), text, textColor, font=fontText)
  11. return cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)
  12. if __name__ == '__main__':
  13. imgPath = "result.jpg"
  14. img = cv2.imread(imgPath)
  15. saveImg = cv2ImgAddText(img, '中国加油!', 50, 100, (255, 0, 0), 50)
  16. # cv2.imshow('display',saveImg)
  17. cv2.imwrite('save.jpg',saveImg)
  18. # cv2.waitKey()