opencv给图片加中文水印

import cv2
import os
import numpy as np
from PIL import Image,ImageFont,ImageDraw


#给图片加水印
def create_watermark(img_path, save_to, text, position):
    # img = cv2.imread(img_path)
    img = cv2.imdecode(np.fromfile(img_path, dtype=np.uint8), -1)
    sp = img.shape
    h = sp[0]
    w = sp[1]
    c = sp[2]
    # 给图片添加文字水印
    # img2 = cv2.putText(img, text, (100, 100), cv2.LINE_AA, 2, (249, 249, 249), 4) #这里不支持中文水印
    # # 保存图片
    # cv2.imwrite(save_to, img2)
    # # 下面是将生成的图片再弹窗中显示
    # cv2.imshow('img', img2)
    # cv2.waitKey(0)
    # cv2.destoryAllWindows('img')

    #基于PIL实现中文水印添加
    pil_img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) #BGR 2 RGB
    font = ImageFont.truetype(font="simfang.ttf", size=20) #windows的字体,linux下换字体
    color = (255, 255, 255)
    pos = (int(w * 0.5) - 50, int(h * 0.5))
    if position == "right_bottom":
        pos = (w-150, h-30)
    draw = ImageDraw.Draw(pil_img)
    draw.text(pos, text, font=font, fill=color)
    cv_img = cv2.cvtColor(np.asarray(pil_img), cv2.COLOR_RGB2BGR)
    cv2.imshow('img', cv_img)

    if os.path.exists(save_to) == False:
        os.mkdir(save_to)
    # cv2.imwrite(save_to + , cv_img) #不支持中文路径
    cv2.imencode(".jpg", cv_img)[1].tofile(save_to + img_path.split("\\")[-1])


if __name__ == "__main__":
        # create_watermark("P:\\0.jpg", "P:\\split\\watermark.jpg", "@古代书法欣赏", "right_bottom")
        #批量处理
        dir = 'P:\\split\\tif_split\\001_0\\'
        list = os.listdir(dir)  # 列出文件夹下所有的目录与文件
        for i in range(0, len(list)):
            path = os.path.join(dir, list[i])
            print("处理文件:%s" % path)
            if os.path.isfile(path):
                try:
                    create_watermark(path, "P:\\split\\watermark\\001_0\\", "@古代书法欣赏", "right_bottom")
                except IOError:
                    print("IOError")

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

yesunx

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

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

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

打赏作者

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

抵扣说明:

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

余额充值