图片固定位置写汉字(水印)

超链接:深度学习工作常用方法汇总,矩阵维度变化、图片、视频等操作,包含(torch、numpy、opencv等)


import os

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


def cv2AddChineseText(img, text, position, textColor=(0, 255, 0), textSize=30):
    if (isinstance(img, np.ndarray)):  # 判断是否OpenCV图片类型
        img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
    # 创建一个可以在给定图像上绘图的对象
    draw = ImageDraw.Draw(img)
    # 字体的格式
    fontStyle = ImageFont.truetype(
        "simsun.ttc", textSize, encoding="utf-8")
    # 绘制文本
    draw.text(position, text, textColor, font=fontStyle)
    # 转换回OpenCV格式
    return cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)


path_ori = r'C:\Users\86182\Desktop\cc_zg\cc_zhgd_yglwkl'
save_path = r'C:\Users\86182\Desktop\水印\cc_zhgd_yglwkl'
# save_path = os.path.join(save_path, path_ori.split('\\')[-1])
box = [1547, 80, 1831, 147]
# dirs = os.lisdir(path_ori)
for root, dirs, files in os.walk(path_ori):
    for file in files:
        if '.jpg' not in file:
            continue
        # save_path = root.replace('JPEGImages', 'JPEGImages_备份')
        if not os.path.exists(save_path):
            os.makedirs(save_path)
        img_path = os.path.join(root, file)
        frame = cv2.imdecode(np.fromfile(img_path, dtype=np.uint8), cv2.IMREAD_COLOR)
        print(img_path)
        cv2.rectangle(frame, (int(box[0]), int(box[1])), (int(box[2]), int(box[3])),
                      (114, 114, 114), -1)
        # cv2.putText(frame, '仅供数据标注使用,请勿商用。', (int(box[0] + 3), int(box[1] + 3)),
        #             0, 5e-3 * 150, (0, 0, 255), 1)
        frame = cv2AddChineseText(frame, '仅供数据标注    使用',
                                  (int(box[0] + 15), int(box[1] + 5)), (255, 0, 0), 30)
        frame = cv2AddChineseText(frame, '请勿商用',
                                  (int(box[0] + 75), int(box[1] + 35)), (255, 0, 0), 30)
        cv2.imencode('.jpg', frame)[1].tofile(os.path.join(save_path, file))
        # frame = cv2.resize(frame, None, fx=0.5, fy=0.5)
        # cv2.imshow('img', frame)
        # cv2.waitKey(0)

你可能感兴趣的:(OpenCV,opencv,计算机视觉,python)