简体   繁体   English

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

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

I am trying to crop the image into 1:1 aspect ratio with the following code.我正在尝试使用以下代码将图像裁剪为 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)

but it is not giving me the right output.但它没有给我正确的 output。 I am using the following image: input我正在使用以下图像:输入

and it gives me the following output: output它给了我以下 output: output

it gives me the right dimensions but not the right output.它给了我正确的尺寸,但不是正确的 output。

Just compare width and height to find which side should be sliced.只需比较宽度和高度即可找到应该切片的一侧。 The crop offset of two side border equals to the difference divided by 2.两侧边框的裁剪偏移量等于差值除以 2。

Numpy 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)

PIL太平船务

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