python opencv 如何给图片添加文字?cv2.putText() PIL

88 篇文章 17 订阅

参考文章1:python如何在图片上添加文字(中文和英文)Python在图片上添加文字的两种方法:OpenCV和PIL

参考文章2:python之------如何在图片上面添加文字(多种类型的文字)【PIL】

参考文章3:python 图片上添加中文文字【PIL】

参考文章4:python-OpenCV之在图片上添加文字(cv.putText())

putText函数doc

opencv版本:4.1.0(不同版本Doc也许不同)

def putText(img, text, org, fontFace, fontScale, color, thickness=None, lineType=None, bottomLeftOrigin=None): # real signature unknown; restored from __doc__
    """
    putText(img, text, org, fontFace, fontScale, color[, thickness[, lineType[, bottomLeftOrigin]]]) -> img
    .   @brief Draws a text string. 绘制文本字符串。
    .   
    .   The function cv::putText renders the specified text string in the image. Symbols that cannot be rendered
    .   using the specified font are replaced by question marks. See #getTextSize for a text rendering code
    .   example.
    ·	
    	函数cv :: putText在图像中呈现指定的文本字符串。 
    	无法使用指定字体呈现的符号将替换为问号。 有关文本渲染代码示例,请参见#getTextSize。
    .   
    .   @param img Image. 图片。
    .   @param text Text string to be drawn. 要绘制的文本字符串。
    .   @param org Bottom-left corner of the text string in the image. 图像中文本字符串的左下角。
    .   @param fontFace Font type, see #HersheyFonts. 字体类型,请参见#HersheyFonts。
    .   @param fontScale Font scale factor that is multiplied by the font-specific base size.
    	字体比例因子乘以特定于字体的基本大小。
    .   @param color Text color. 文字颜色。
    .   @param thickness Thickness of the lines used to draw a text. 用于绘制文本的线条的粗细。
    .   @param lineType Line type. See #LineTypes 线型。 请参阅#LineTypes
    .   @param bottomLeftOrigin When true, the image data origin is at the bottom-left corner. Otherwise, it is at the top-left corner.
    	如果为true,则图像数据原点位于左下角。 否则,它位于左上角。
    """
    pass

Doc中所指#HersheyFonts:链接
在这里插入图片描述
在这里插入图片描述
Doc中所指#LineType:链接
在这里插入图片描述
在这里插入图片描述

示例代码

功能

将上上级imgs文件夹内的2000张图片全部打上标记,显示其模糊程度值(越小越模糊)(用于展示用)

code

# -*- encoding: utf-8 -*-
"""
@File    : judge_the_picture_blur.py
@Time    : 2019/10/25 8:52
@Author  : Dontla
@Email   : sxana@qq.com
@Software: PyCharm
"""
import cv2
import os


# 返回指定路径图像的拉普拉斯算子边缘模糊程度值
def getImageVar(img_path):
    image = cv2.imread(img_path)
    img2gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    imageVar = cv2.Laplacian(img2gray, cv2.CV_64F).var()
    return imageVar


# 返回给定文件夹下所有图片的路径列表
def listFolderImgPath(folder_img_path):
    img_path_list = []
    for filename in os.listdir(folder_img_path):
        filepath = os.path.join(folder_img_path, filename)
        img_path_list.append(filepath)
    return img_path_list


# 给单张图片添加文字(图片路径,文字)
def writeText(img_path, text):
    # 加载背景图片
    # img的类型是np.ndarray数组
    img = cv2.imread(img_path)
    # 在图片上添加文字信息
    # 颜色参数值可用颜色拾取器获取((255,255,255)为纯白色)
    # 最后一个参数bottomLeftOrigin如果设置为True,那么添加的文字是上下颠倒的
    composite_img = cv2.putText(img, text, (100, 680), cv2.FONT_HERSHEY_SIMPLEX,
                                2.0, (255, 255, 255), 5, cv2.LINE_AA, False)
    cv2.imwrite(img_path, composite_img)


# 文件夹路径
folder_img_path = '../../imgs/'

# 图片路径
img_path = '../../imgs/f_cotton-g_top (813).jpg'

# print(getImageVar(img_path))

# print(listFolderImgPath(folder_img_path))

# 获取图片路径列表
img_path_list = listFolderImgPath(folder_img_path)

# 循环处理每张图片
for img_path in img_path_list:
    # 获取该张图片模糊值
    imageVar = getImageVar(img_path)
    # 创建需写入文字信息
    text = 'The fuzzy is: {:.2f}'.format(imageVar)
    # 将文字写入图片
    writeText(img_path, text)

    # img = cv2.imread(img_path)
    # cv2.namedWindow('image', cv2.WINDOW_AUTOSIZE)
    # cv2.imshow('image', img)
    # cv2.waitKey(1)

最终效果

在这里插入图片描述
在这里插入图片描述

  • 7
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
### 回答1: 要在Python中使用cv2.putText显示中文,需要先安装中文字体。可以通过以下步骤来实现: 1. 下载中文字体文件(例如:SimHei.ttf)并将其保存在项目文件夹中。 2. 在代码中导入cv2PIL库: ```python import cv2 from PIL import ImageFont, ImageDraw, Image ``` 3. 创建一个PIL图像对象并加载字体: ```python img_pil = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) font = ImageFont.truetype('SimHei.ttf', 40) ``` 4. 创建一个PIL绘图对象并使用puttext方法添加中文文本: ```python draw = ImageDraw.Draw(img_pil) draw.text((x, y), text, font=font, fill=(255, 0, 0)) ``` 5. 将PIL图像对象转换回OpenCV图像对象: ```python img = cv2.cvtColor(np.array(img_pil), cv2.COLOR_RGB2BGR) ``` 完整代码示例: ```python import cv2 import numpy as np from PIL import ImageFont, ImageDraw, Image # 加载图像 img = cv2.imread('test.jpg') # 创建PIL图像对象并加载字体 img_pil = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) font = ImageFont.truetype('SimHei.ttf', 40) # 创建PIL绘图对象并使用puttext方法添加中文文本 draw = ImageDraw.Draw(img_pil) text = '你好,世界!' x, y = 50, 50 draw.text((x, y), text, font=font, fill=(255, 0, 0)) # 将PIL图像对象转换回OpenCV图像对象 img = cv2.cvtColor(np.array(img_pil), cv2.COLOR_RGB2BGR) # 显示图像 cv2.imshow('image', img) cv2.waitKey(0) cv2.destroyAllWindows() ``` ### 回答2: 在使用OpenCVPython接口进行图像处理的过程中,有时需要向图像中添加中文文字。然而,由于Python默认使用的是ASCII编码,所以无法直接使用cv2.putText函数显示中文。 解决这个问题的方法有很多,下面介绍两种比较常用的方法: 方法一:使用第三方库Pillow Pillow是Python中一个非常常用的图像处理库,它也可以用来在图像中添加中文文字。 首先需要安装Pillow库,在命令行中输入以下命令: ``` pip install Pillow ``` 安装完成后,可以使用以下代码向图像中添加中文文字: ```python from PIL import Image, ImageDraw, ImageFont import cv2 # 加载图像 img = cv2.imread('test.jpg') # 将BGR格式转为RGB格式 img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # 在Pillow中创建图像对象 pil_img = Image.fromarray(img_rgb) # 创建绘图对象 draw = ImageDraw.Draw(pil_img) # 设置中文字体 font = ImageFont.truetype('msyh.ttc', 30) # 绘制中文文字 text = '测试中文' draw.text((50, 50), text, font=font, fill=(255, 0, 0)) # 将Pillow中的图像对象转为OpenCV中的图像格式 img_with_text = cv2.cvtColor(np.asarray(pil_img), cv2.COLOR_RGB2BGR) # 显示图像 cv2.imshow('image with text', img_with_text) cv2.waitKey(0) cv2.destroyAllWindows() ``` 在以上代码中,使用Pillow库中的ImageDraw对象创建了一个图像实例,设置好字体后调用text()方法绘制中文文字。最后将Pillow库中的实例转换为OpenCV中的格式即可在图像上显示中文文字。 方法二:使用cv2的putText函数配合自定义字体文件 这种方法需要事先准备好自己的中文字体文件,这里以微软雅黑字体为例,具体操作过程如下: 首先下载微软雅黑字体文件msyh.ttc,放在当前工程目录下。 在代码中添加如下代码: ```python font = cv2.FONT_HERSHEY_SIMPLEX # 字体类型 text = '测试中文' # 中文文字 position = (50, 50) # 文字位置 fontScale = 1 # 字体大小 fontColor = (0, 0, 255) # 字体颜色 thickness = 2 # 字体线条厚度 cv2.putText(img, text, position, font, fontScale, fontColor, thickness) ``` 以上代码中,需要将字体类型设置为cv2.FONT_HERSHEY_SIMPLEX,使用cv2.putText函数绘制中文文字,并同时设置好文字位置、字体大小、字体颜色和线条厚度等参数。这里笔者将文字的位置设置为(50, 50),文字大小设置为1,字体颜色设置为红色,线条厚度设置为2,可以自己根据需要进行调整。 完整代码如下: ```python import cv2 import numpy as np # 加载图像 img = cv2.imread('test.jpg') # 将BGR格式转为RGB格式 img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # 将RGB格式转为灰度图像 gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 将灰度图像转为BGR格式 gray_bgr = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR) # 在灰度图像上添加中文文字 font = cv2.FONT_HERSHEY_SIMPLEX text = '测试中文' position = (50, 50) fontScale = 1 fontColor = (0, 0, 255) thickness = 2 cv2.putText(gray_bgr, text, position, font, fontScale, fontColor, thickness) # 显示图像 cv2.imshow('image', img) cv2.imshow('gray image with chinese text', gray_bgr) cv2.waitKey(0) cv2.destroyAllWindows() ``` 使用以上代码可以在灰度图像中添加中文文字。一定要注意字体文件路径和编码类型,防止中文乱码的出现。 总之,在OpenCV Python接口中显示中文文字,可以使用Pillow库或自定义字体文件配合使用cv2.putText函数来实现。希望本文的方法可以帮到大家,也希望大家还有其他更好的解决方案,可以分享给大家。 ### 回答3: 在Python中使用OpenCVcv2显示中文比较麻烦,需要将文字字符串转换成Unicode编码,并且选择合适的字体,使用cv2.putText()函数显示。 首先需要使用Pillow库(Python Image Library)中的ImageFont和ImageDraw类来创建一个PILPython Imaging Library)图像,再利用Pillow库的tobytes()函数将图像转为numpy数组,最后再使用cv2.imshow()函数显示图片。 以下是一个大致的方法: 1、导入需要的库: ``` import cv2 from PIL import Image, ImageFont, ImageDraw import numpy as np ``` 2、创建一个PIL图像,并在图片上绘制中文字符串: ``` # 创建一个100x100的纯白色图像 image = Image.new('RGB', (100, 100), (255, 255, 255)) # 中文字体设置 fontpath = 'simhei.ttf' # 字体文件路径 font = ImageFont.truetype(fontpath, 30) # 字体大小 # 绘制中文字符 draw = ImageDraw.Draw(image) text = "你好,世界!" draw.text((10, 10), text, font=font, fill=(0, 0, 0)) ``` 3、将PIL图像对象转换成numpy数组: ``` array = np.array(image) # 转为numpy数组 ``` 4、将numpy数组转换成OpenCV的图像对象: ``` cv2.imshow('image', array) # 显示OpenCV处理后的图像 cv2.waitKey() # 等待键盘按键 cv2.destroyAllWindows() # 关闭所有窗口 ``` 这样就可以在OpenCV的窗口里显示文字符串了。 注意:在Windows中,需要安装中文字体文件,比如SimHei.ttf,才能正确显示中文。同样,也可以使用微软雅黑字体微软雅黑.ttf或其他已经安装的中文字体。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Dontla

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值