Python Forum
cropping a picture (always square) - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: cropping a picture (always square) (/thread-12036.html)



cropping a picture (always square) - Leon - Aug-06-2018

Hello,
I'am new to this forum and new into Python .

I want to cropping a picture automatic with a python script.
On the picture are flowers and i want only the flowers on without white edges.
I've found the perfect code to do it.


from PIL import Image, ImageChops

def trim(im) :
    print ('Foto Bewerking gestart')
    bg = Image.new(im.mode, im.size, im.getpixel((0,0)))
    diff = ImageChops.difference(im, bg)
    diff = ImageChops.add(diff, diff, 1.8, -100)
    bbox = diff.getbbox()
    print (bbox)
    if bbox:
        return im.crop(bbox)
    
    
    
    

if __name__ == "__main__":
    bg = Image.open("test.jpg")  # The image to be cropped
    new_im = trim(bg)
    new_im.show ()
    new_im.save ("geknipt.jpg")  # result cropping
Its works great the only thing is the picture must Always be square without streching or disform the picture.

So i've set the print function to show the coordinates print (bbox)

Whit this data i can calculate how to crop the picture in the best way.

So the starting picture is 4000x4000 pixels.
If i do the cropping cycle it become 2000x3000 pixels.
Simpel math let see there is a difference of 1000.
So i need o add on bothe side 500 pixels to get the right cropping and make it square.


How can i do it ?


RE: cropping a picture (always square) - Leon - Aug-13-2018

Nobody see a sollution for my problem ?