繁体   English   中英

如何使用 Python 中的枕头以 1:1 的纵横比裁剪图像?

[英]How can I crop an Image with 1:1 aspect ratio using pillow in Python?

我正在尝试使用以下代码将图像裁剪为 1:1 的纵横比。

from PIL import Image

def crop_image(image):
    width, height = image.size
    print(width, height)
    aspect_ratio = width/float(height)

    if aspect_ratio < 1:
        bottom_offset = height/2 - width/2
        top = height - bottom_offset
        bottom = top + width
        left = 0
        right = left+width
        print((top, bottom, left, right))
        new_image = image.crop((left,top, right, bottom))
        print(new_image.size)
        new_image.save("new.jpg")

image = Image.open('test.jpg')
crop_image(image)

但它没有给我正确的 output。 我正在使用以下图像:输入

它给了我以下 output: output

它给了我正确的尺寸,但不是正确的 output。

只需比较宽度和高度即可找到应该切片的一侧。 两侧边框的裁剪偏移量等于差值除以 2。

Numpy

from PIL import Image
import numpy as np
def crop_image(img):
    width, height = image.size
    if width == height:
        return img
    img = np.array(img)
    offset  = int(abs(height-width)/2)
    if width>height:
        img = img[:,offset:(width-offset),:]
    else:
        img = img[offset:(height-offset),:,:]
    return Image.fromarray(img)

image = Image.open(r"test.jpg")
crop_image(image)

太平船务

from PIL import Image
image = Image.open(r"test.jpg")
def crop_image(image):
    width, height = image.size
    if width == height:
        return image
    offset  = int(abs(height-width)/2)
    if width>height:
        image = image.crop([offset,0,width-offset,height])
    else:
        image = image.crop([0,offset,width,height-offset])
    return image
image = Image.open(r"test.jpg")
crop_image(image)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM