可运行下面实例实现批量合成:
from PIL import Image, ImageDraw, ImageFont
num = [1, 2, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
for i in num:
# 打开三张灰度图像
image1 = Image.open(f"dataset/my_test/Low_dose/{i}.png").convert("L")
image2 = Image.open(f"dataset/my_test/High_dose/{i}.png").convert("L")
image3 = Image.open(f"dataset/my_test/results-fbpl1/{i}_SR.png").convert("L")
# 调整图像尺寸为相同大小
width, height = image1.size
image2 = image2.resize((width, height))
image3 = image3.resize((width, height))
# 创建新的合成图像,增加间隙
padding = 40
combined_width = width * 3 + padding * 4
combined_height = height + padding * 2
combined_image = Image.new("L", (combined_width, combined_height))
# 将图像依次粘贴到合成图像中,加入间隙
combined_image.paste(image1, (padding, padding))
combined_image.paste(image2, (width + padding * 2, padding))
combined_image.paste(image3, (width * 2 + padding * 3, padding))
# 在合成图像下方标注信息,调整字体大小和颜色
draw = ImageDraw.Draw(combined_image)
font = ImageFont.truetype("arial.ttf", 30)
text_color = 255
# 计算文本宽度
text1_width, text1_height = draw.textsize("Low", font=font)
text2_width, text2_height = draw.textsize("High", font=font)
text3_width, text3_height = draw.textsize("Fixed", font=font)
# 计算文本位置并绘制文本
draw.text((padding + width // 2 - text1_width // 2, height + padding), "Low", font=font, fill=text_color)
draw.text((width + padding * 2 + width // 2 - text2_width // 2, height + padding), "High", font=font, fill=text_color)
draw.text((width * 2 + padding * 3 + width // 2 - text3_width // 2, height + padding), "Fixed", font=font,
fill=text_color)
# 保存合成图像为PNG格式
combined_image.save(f"dataset/my_test/my_show/{i}.png")