需求描述
給圖片加上說明,不改變圖片大小
思路
讀取圖片,給圖片加白色背景,將文字寫在白色畫布上
代碼
使用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'
# 重新畫圖 統(tǒng)一尺寸
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
出處:http://www.reibang.com/p/1843253e9b46
版權(quán)所有凿试,歡迎保留原文鏈接進(jìn)行轉(zhuǎn)載:)