Python根据面积匹配两图最佳大小

文章目录

  • 问题描述
  • 解决方案
  • 参考文献

问题描述

foreground.png
在这里插入图片描述

background1.png
Python根据面积匹配两图最佳大小_第1张图片
background2.png
Python根据面积匹配两图最佳大小_第2张图片




解决方案

  1. 找出面积较大图片,等待缩小
  2. 比较宽优先和高优先的面积
  3. 调整高或宽
from PIL import Image


def match_size(image1, image2):
    '''匹配两图,根据面积返回等比调整宽高后的两图'''
    (width1, height1), (width2, height2) = image1.size, image2.size
    area1, area2 = width1 * height1, width2 * height2
    width, height, large = (width1, height1, image2) if area1 < area2 else (width2, height2, image1)  # 调整大图
    _width, _height = large.size  # 大图宽高
    area_width, area_height = _width * height, _height * width  # 宽优先和高优先面积
    _width, _height = (width, width / _width * _height) if area_width > area_height else (
        height / _height * _width, height)
    size = (int(_width), int(_height))
    image1, image2 = (image1, image2.resize(size)) if area1 < area2 else (image1.resize(size), image2)  # 调整尺寸
    return image1, image2


background1 = Image.open('background1.png')  # 背景图1
background2 = Image.open('background2.png')  # 背景图2
foreground = Image.open('foreground.png')  # 前景图
background1, foreground = match_size(background1, foreground)
background2, foreground = match_size(background2, foreground)
print(foreground.size, background1.size, background2.size)
# (400, 400) (400, 307) (307, 400)




参考文献

  1. Pillow (PIL) 文档

你可能感兴趣的:(Python,PIL,python,PIL,计算机视觉)