首页 > 解决方案 > 裁剪图像的中心

问题描述

我如何使用crop()来自的功能PIL函数裁剪 224*224 图像的中心。

给定输入图像:

320*240,裁剪这个224*224尺寸图片的中心

预期输出:

裁剪尺寸为 224*224 的图像中心

标签: python-imaging-librarypython-2.x

解决方案


从这张图片开始,彩色部分为 224x224,黑色背景为 320x240。

在此处输入图像描述

我会numpy像这样裁剪:

#!/usr/local/bin/python3
from PIL import Image
import numpy as np

# Open the image and convert to numpy array
im=Image.open('start.png')
im=np.array(im)

# Work out where top left corner is
y=int((320-224)/2)
x=int((240-224)/2)

# Crop, convert back from numpy to PIL Image and and save
cropped=im[x:x+224,y:y+224]
Image.fromarray(cropped).save('result.png')

在此处输入图像描述


推荐阅读