2025年4月21日 星期一 乙巳(蛇)年 正月廿二 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > Python

python --给图片加文字

时间:08-16来源:作者:点击数:27
CDSY,CDSY.XYZ

python --给图片加文字

  • import cv2
  • from PIL import ImageFont, ImageDraw, Image
  • import numpy as np
  • bk_img = cv2.imread(r"C:\Users\ht-desktop-001\Desktop\088.png")
  • #设置需要显示的字体
  • fontpath = "msyhbd.ttc"
  • font = ImageFont.truetype(fontpath, 32)
  • img_pil = Image.fromarray(bk_img)
  • draw = ImageDraw.Draw(img_pil)
  • #绘制文字信息
  • draw.text((1, 3), "Hello World", font = font, fill = (0, 0, 0))
  • draw.text((100, 350), "你好", font = font, fill = (255, 255, 255))
  • bk_img = np.array(img_pil)
  • cv2.imshow("add_text",bk_img)
  • cv2.waitKey()
  • cv2.imwrite("add_text.jpg",bk_img)

方法二

  • pip install opencv-python

.利用putText方法来实现在图片的指定位置添加文字

putText(img,text,org,fontFace,fontScale,color,thickness=None,lineType=None,bottomLeftOrigin=None)

img:操作的图片数组

text:需要在图片上添加的文字

fontFace:字体风格设置

fontScale:字体大小设置

color:字体颜色设置

thickness:字体粗细设置

案例

  • import cv2
  • #加载背景图片
  • bk_img = cv2.imread("background.jpg")
  • #在图片上添加文字信息
  • cv2.putText(bk_img,"Hello World", (100,300), cv2.FONT_HERSHEY_SIMPLEX,
  • 0.7,(255,255,255), 1, cv2.LINE_AA)
  • #显示图片
  • cv2.imshow("add_text",bk_img)
  • cv2.waitKey()
  • #保存图片
  • cv2.imwrite("add_text.jpg",bk_img)
在这里插入图片描述

注:在使用putText方法在图片上添加文字的时,无法直接添加中文和无法导入字体文件,接下来我们利用另一库PIL来解决这个问题

PIL方法

  • from PIL import Image, ImageDraw, ImageFont
  • # Open the image
  • image = Image.open(r"D:\yi\yan_lian\media\share\2_qr.jpg")
  • # Create a drawing object
  • draw = ImageDraw.Draw(image)
  • text = "10000"
  • # Define the font style and size
  • font = ImageFont.truetype(r"D:\yi\yan_lian\SIMLI.TTF", 60)
  • # Define the position where the text will be added
  • position = (410, 1100)
  • # Define the color of the text
  • color = (0, 0, 0) # white color
  • # Add the text to the image
  • draw.text(position, text, font=font, fill=color)
  • # Save the modified image
  • image.show()
  • # image.save("modified_image.jpg")
CDSY,CDSY.XYZ
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门
本栏推荐