如何索引图像 (PIL) 类型数组

How to Index an Image (PIL) type array

说我有两个图像连接,所以整个图像的形状 (256,512) 像这样:[X|X]

我希望能够做到这一点:

from PIL import Image
both_image = Image.open(path)
img_left = both_image[:,:256]
img_right = both_image[:,256:]

但是*** TypeError: 'PngImageFile' object is not subscriptable

要修复它,我正在写:both_image = np.array(Image.open(path)) 并在末尾使用 Image.fromarray()

有没有更好的方法,不用在 Image 类型和 numpy 数组之间来回切换?

我会使用 Image.crop 并裁剪 both_image 两次。

来自 Pllow 文档:

Image.crop(box=None)

Returns a rectangular region from this image. The box is a 4-tuple defining the left, upper, right, and lower pixel coordinate.

使用相同的设置:

from PIL import Image
both_image = Image.open(path)

裁剪左图,从 (0,0) 到 (256,256):

img_left = both_image.crop((0,0,256,256))

裁剪右图,从 (256,0) 到 (512,256):

img_right = both_image.crop((256,0,512,256))