# -*- coding: utf-8 -*-
"""
Created on Tue Apr 20 16:40:53 2021
两张图片重叠,加字
@author: xf
"""
import cv2
import os
import numpy as np
from PIL import Image, ImageDraw, ImageFont
#图片名
picture_name1 = "bizhi1.jpg"
picture_name2 = "11.png"
picture_name3 = "img11.jpg"
picture_name4 = "img21.jpg"
picture_name5 = "my.jpg"
#图片路径
path = r"F:\pypicture"
# 生成图片
img1 = cv2.imread(path + "\\" +picture_name1)
img2 = cv2.imread(path + "\\" +picture_name2)
# =============================================================================
# 在图片上写字
# =============================================================================
def cv2ImgAddText(img, text, left, top, textColor=(0, 255, 0), textSize=20):
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((left, top), text, textColor, font=fontStyle)
# 转换回OpenCV格式
return cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)
img = cv2ImgAddText(img1, "2021.04.20", 500, 500, (20, 255 , 200), 100)
# cv2.imshow("img1",img1)
# cv2.waitKey()
cv2.imwrite(path + "\\" +"img11.jpg",img)
img1 = cv2.imread(path + "\\" +picture_name3)
# =============================================================================
# 缩放使用cv2.resize()函数,resize函数里的size第一个是宽(列),第二个是高(行)。
# =============================================================================
img11 = cv2.resize(img1, (1000, 600))
img21 = cv2.resize(img2, (1000, 600))
cv2.imwrite(path + "\\" +picture_name3,img11)
cv2.imwrite(path + "\\" +picture_name4,img21)
# cv2.imshow("img11", img11)
# cv2.waitKey()
# cv2.imshow("img21", img21)
# cv2.waitKey()
img11 = Image.open(path + "\\" +picture_name3)
img21 = Image.open(path + "\\" +picture_name4)
merge = Image.blend(img11, img21,0.7)
merge.save(path + "\\" +picture_name5)
img21 = cv2.imread(path + "\\" +picture_name5)
cv2.imshow("img21", img21)
cv2.waitKey()
# 删除文件
os.remove(path + "\\" +picture_name3)
os.remove(path + "\\" +picture_name4)