'PIL Image not cropping the way I want

I was trying to make a contact sheet of a colored image. fully desaturated to full color, but the problem is the output is 10 images of the first cropped image.

Here is the code:

import PIL
from PIL import ImageEnhance
from PIL import Image

image =  Image.open("img.jpg").convert("RGB")

contact_sheet = PIL.Image.new(image.mode,(1920,1080))

enhancer = ImageEnhance.Color(image)

images = []
current_location = 0   
for i in range(10):
    images.append(enhancer.enhance(i/10))

for img in images:
    contact_sheet.paste(img,(current_location,0))
    image.crop((current_location,0,current_location+192,0+1080))
    current_location+=192 

imagesave = contact_sheet.save("CroppedContactSheet.jpg")

here is the cropped image:



Solution 1:[1]

You need to assign the result of the crop function to a variable. The image is not altered by the crop function, but the cropped version is returned, see also the docs, using this input:

enter image description here

And this modified code:

import PIL
from PIL import ImageEnhance
from PIL import Image

image =  Image.open("img.jpg").convert("RGB")

contact_sheet = PIL.Image.new(image.mode,(1920,1080))

enhancer = ImageEnhance.Color(image)

images = []
current_location = 0   
for i in range(10):
    images.append(enhancer.enhance(i/10))

for img in images:
    # Changed here slightly, current_slice is what we want to paste into the new image
    current_slice = img.crop((current_location,0,current_location+192,0+1080))
    contact_sheet.paste(current_slice,(current_location,0))
    current_location+=192

#display(contact_sheet)
imagesave = contact_sheet.save("CroppedContactSheet.jpg")


We get this output:

enter image description here

Image taken from http://www.desktopwallpaperhd.net/view/raptor-sample-ford-auto-cartoon-205618.html

Addition:

I don't know if it was intended, but from your question it sounds like you wanted to go from enhancer.enhance(0) to enhancer.enhance(1), but in the code you provided you are going from 0 to 9/10, so the last slice is not at full color, but at 90%. If we change the code to enhancer.enhance(i/9), then the ouptut is:

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1