当前位置: 代码迷 >> 综合 >> python在图片上写汉字,并竖向排列在图片上
  详细解决方案

python在图片上写汉字,并竖向排列在图片上

热度:73   发布时间:2023-10-19 18:17:41.0

当我们用opencv在图片上写汉字,使用的是putText,会遇到只能写英文,写中文的话,会遇到报错。

这个时候我们只需要转成PIL格式,对其输入中文,再转会opencv格式就好

代码如下:

import cv2
import os
import numpy as np
from PIL import ImageFont, ImageDraw, Imagefps = 30
size = (1280, 720)
name = 1
# videowriter = cv2.VideoWriter("result.mp4",-1, fps, size)img = np.ones((720, 1280, 3), dtype=np.uint8)*255
txt = '这人间袅袅炊烟'#设置需要显示的字体
fontpath = "font/simhei.ttf" # 32为字体大小
font = ImageFont.truetype(fontpath, 32)
img_pil = Image.fromarray(img)     #openc转PIL
draw = ImageDraw.Draw(img_pil)
draw.text((100, 350), txt, font = font, fill = (255, 0, 0))
img = np.array(img_pil)   #PIL转opencv#显示图片
cv2.imshow("img",img)
cv2.waitKey(0)

然后是效果图

  相关解决方案