完成的目标
可以看以下的过程,比如有两张图像A和B,希望变为AB融合的图像:
代码实现【代码里面可以实现为图像添加文本描述】
# -*- coding:utf-8 -*-
from skimage import io
import cv2
from PIL import Image,ImageDraw,ImageFont
def blend_two_images(img_file1,img_file2,img_file3,text, left, top, text_color=(255, 0, 0), text_size=13):
img1 = Image.open(img_file1)
#print(img1.shape)
img1 = img1.convert('RGBA')
img2 = Image.open(img_file2)
img2 = img2.convert('RGBA')
# 尺寸调整,如果两幅图像大小不一样,需要 resize
#img1 = img1.resize((224, 224))
#img2 = img2.resize((224, 224))
img = Image.blend(img1, img2, 0.5)
# 创建一个可以在给定图像上绘图的对象
draw = ImageDraw.Draw(img)
# 字体的格式 Centos中都在字体可用命令 fc-list 查询,选中一个合适的字体就行
fontStyle = ImageFont.truetype("/usr/share/fonts/dejavu/DejaVuSerif-Bold.ttf", text_size, encoding="utf-8")
# 绘制文本
draw.text((left, top), text, text_color, font=fontStyle)
img.show()
img.save(img_file3)
if __name__=="__main__":
img_file1=r"./ori.jpg"
img_file2=r"./heatmap2.jpg"
img_file3=r"./test3.png"
blend_two_images(img_file1,img_file2,img_file3,"test", 50, 100, text_color=(255, 0, 0), text_size=50)