python之不影响图片大小并增加图片注释

需求描述

给图片加上说明,不改变图片大小

思路

读取图片,给图片加白色背景,将文字写在白色画布上

代码

使用opencv + PIL

# -*- coding: UTF-8 -*-
# __author__ = 'shelly.si'
import cv2
import numpy as np
from PIL import Image, ImageDraw, ImageFont


def img_mark():
    """批量添加文字"""
    raw_img_path = r'./flower.png'
    new_image_path = r'./flower_mid.jpg'
    final_path = r'./flower_new.jpg'
    # 重新画图 统一尺寸
    org_image_path = raw_img_path
    image = cv2.imread(org_image_path)
    h = image.shape[0]
    w = image.shape[1]
    img_new_white = img_resize_to_target_white(image, h, w)
    cv2.imwrite(new_image_path, img_new_white)
    cv2.waitKey()
    part_key = '向日葵'
    read_txt(part_key, new_image_path, final_path, h)


def img_resize_to_target_white(image, h, w):
    target = np.ones((h+150, w), dtype=np.uint8) * 255
    ret = cv2.cvtColor(target, cv2.COLOR_GRAY2BGR)
    for i in range(h+150):
        for j in range(w):
            if (i < h) and (j < w):

                ret[i, j, 0] = image[i, j, 0]
                ret[i, j, 1] = image[i, j, 1]
                ret[i, j, 2] = image[i, j, 2]
            else:
                ret[i, j, 0] = 255
                ret[i, j, 1] = 255
                ret[i, j, 2] = 255
    return ret


def read_txt(part_key, new_image_path, final_path, h):
    # 加载最终图片
    org_image_path = new_image_path
    bk_img = cv2.imread(org_image_path)
    frame = cv2.cvtColor(bk_img, cv2.COLOR_BGR2RGB)
    pilimg = Image.fromarray(frame)
    draw = ImageDraw.Draw(pilimg)
    font = ImageFont.truetype("simhei.ttf", 20, encoding="utf-8")
    # 在图片上添加文字信息
    key_point = (2, h+2*22)
    draw.text(key_point, part_key, (0, 0, 0), font=font)
    frame = cv2.cvtColor(np.array(pilimg), cv2.COLOR_RGB2BGR)
    # 保存图片
    cv2.imwrite(final_path, frame)


if __name__ == '__main__':
    img_mark()

原图

flower.png

效果图

flower_new.jpg

作者:g_s_007
出处:https://www.jianshu.com/p/1843253e9b46
版权所有,欢迎保留原文链接进行转载:)

你可能感兴趣的:(python之不影响图片大小并增加图片注释)