web-dev-qa-db-ja.com

PILを使用して中央で画像を切り抜く

中央で画像をトリミングするにはどうすればよいですか?ボックスが左、上、右、下のピクセル座標を定義する4タプルであることは知っていますが、これらの座標を取得して中央で切り取る方法がわかりません。

19
user2401069

トリミングするサイズがわかっていると仮定すると(new_width X new_height):

import Image
im = Image.open(<your image>)
width, height = im.size   # Get dimensions

left = (width - new_width)/2
top = (height - new_height)/2
right = (width + new_width)/2
bottom = (height + new_height)/2

# Crop the center of the image
im = im.crop((left, top, right, bottom))

小さな画像を大きくトリミングしようとすると、これは壊れますが、それを試さないと仮定します(または、その場合は画像をトリミングせずにキャッチできます)。

56
Chris Clarke

提案されたソリューションの潜在的な問題の1つは、目的のサイズと古いサイズの間に奇妙な違いがある場合です。両側に半分のピクセルを配置することはできません。ピクセルを追加する側を選択する必要があります。

水平方向に奇数の違いがある場合、以下のコードは余分なピクセルを右に配置し、垂直に奇数の違いがある場合、余分なピクセルは下に移動します。

import numpy as np

def center_crop(img, new_width=None, new_height=None):        

    width = img.shape[1]
    height = img.shape[0]

    if new_width is None:
        new_width = min(width, height)

    if new_height is None:
        new_height = min(width, height)

    left = int(np.ceil((width - new_width) / 2))
    right = width - int(np.floor((width - new_width) / 2))

    top = int(np.ceil((height - new_height) / 2))
    bottom = height - int(np.floor((height - new_height) / 2))

    if len(img.shape) == 2:
        center_cropped_img = img[top:bottom, left:right]
    else:
        center_cropped_img = img[top:bottom, left:right, ...]

    return center_cropped_img
7
Dean Pospisil

これは私が探していた機能です:

from PIL import Image
im = Image.open("test.jpg")

crop_rectangle = (50, 50, 200, 200)
cropped_im = im.crop(crop_rectangle)

cropped_im.show()

別の回答 から取得

3
penduDev