【问题标题】:How to keep image alignment when cropping in Python?在 Python 中裁剪时如何保持图像对齐?
【发布时间】:2013-09-25 23:47:03
【问题描述】:

我正在尝试在 Python 中裁剪和调整图像大小,我希望它们采用固定格式 之后(47x62 像素)。但是,如果原始图像是横向的,我的算法不起作用,会有空白区域。

import Image, sys

MAXSIZEX = 47
MAXSIZEY = 62

im = Image.open(sys.argv[1])
(width, height) = im.size

ratio = 1. * MAXSIZEX / MAXSIZEY

im = im.crop((0, 0, int(width*ratio), int(height*ratio)))
im = im.resize((MAXSIZEX, MAXSIZEY), Image.ANTIALIAS)

im.save(sys.argv[2])

我希望调整后的图像完全为 47x62 - 应该没有可见的空白区域。

【问题讨论】:

    标签: python html css image user-experience


    【解决方案1】:

    选择 x/y 作为缩放比例是一个隐含的假设,即相对于目标分辨率而言,源的 y 维度始终小于源的 x 维度。首先,确定要缩放的维度,然后裁剪:

    width_count = float(width) / MAXSIZEX
    height_count = float(height) / MAXSIZEY
    if width_count == height_count:
        pass
    elif width_count < height_count:
        im = im.crop(0, 0, width, int(width_count * height / height_count))
    else:
        im = im.crop(0, 0, int(height_count * width / width_count), height)
    

    现在您知道您拥有与您的目标纵横比匹配的原始子图像的最大子图像,因此您可以在不扭曲图像的情况下调整大小。

    【讨论】:

      【解决方案2】:

      您应该首先检查MAXSIZEX 是否大于宽度或MAXSIZEY 是否大于高度。如果他们首先重新缩放图像然后进行裁剪:

      MAXSIZEX = 64
      MAXSIZEY = 42
      width, height = im.size
      
      xrat = width / float(MAXSIZEX)
      yrat = height / float(MAXSIZEY)
      
      if xrat < 1 or yrat < 1:
          rat = min(xrat, yrat)
          im = im.resize((int(width / rat), int(height / rat)))
      res = im.crop((0, 0, MAXSIZEX, MAXSIZEY))
      res.show()
      

      【讨论】:

      • +1 表示旧的、不言自明的代码。从内部触摸与从外部触摸
      猜你喜欢
      • 1970-01-01
      • 2019-01-11
      • 2011-09-21
      • 2019-06-11
      • 2021-07-26
      • 2020-10-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多