在 Pillow 中重复使用 crop 方法的问题(Python's PIL fork)

Problems with repeat use of crop method in Pillow (Python's PIL fork)

我有一些代码使用 Pillow 的 crop 方法将单个图像拆分为多个子图像。我的代码类似于以下内容:

from PIL import Image
from PIL import ImageTk
import Tkinter    


# Open image from file path
baseimg = Image.open("PathToLargeImage.tif")

# Get image attributes
height = baseimg.height
width = baseimg.width

# Create a list of sub-images
subimages = []
for y in range(0, height, 50):
    subimage = baseimg.crop((0, y, width, 10))
    subimage.load()  # Call load on sub-image to detach it from baseimg
    subimages.append(subimage)
    showimage(subimage)

当我调用显示 subimage 时,第一个子图像将正确显示,然后所有后续子图像的高度将为零(从调试中发现 PyCharm) 显示不正常

showimage函数使用Tkinter,如下:

def showimage(img):
    # Build main window
    root = Tkinter.Tk()
    # Convert image
    tkimage = ImageTk.PhotoImage(img)
    # Add image on window
    Tkinter.Label(root, image=tkimage).pack()
    # Start gui loop
    root.mainloop()

问题出在这一行:

 subimage = baseimg.crop((0, y, width, 10))

如果您在 http://effbot.org/imagingbook/image.htm#tag-Image.Image.crop 查看裁剪文档 你会看到它不需要框的宽度和高度来裁剪, 相反,它的绝对坐标。

所以,你只需要相应地改变你的电话:

subimage = baseimg.crop((0, y, width, y + 10))