简体   繁体   中英

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

I have some code that splits a single image into multiple sub-images using Pillow's crop method. My code is similar to the following:

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)

When I make a call to display subimage the first sub-image will display properly, then all the following sub-images will have a zero height (discovered from debugging with PyCharm) and display improperly.

The showimage function uses Tkinter and is as follows:

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

The problem is in this line:

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

If you check the documentation for crop at http://effbot.org/imagingbook/image.htm#tag-Image.Image.crop you will see it does not take the width and Height of the box to crop, rather, the absolute coordinates for it.

So, you just should have to change your call accordingly:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM