How to crop a region selected with mouse click, using Python Image Library?

Is there a way to select a region in a image with mouse click and crop these region using python PIL ? How can i do it?

Thanks

Upvotes: 3

Views: 15620

Answers (3)

Sam Jett
Sam Jett

Reputation: 831

I tried to make a little tool like this to run in the Jupyter ecosystem, so that you could crop the images and then use the cropped results later on in the same notebook. It's designed to work for many images, to let you crop each of them sequentially. Check it out and see if it works for you. Can install via pip install interactivecrop, but you'll want to check out the blog post for usage instructions.

Upvotes: 1

Permafacture
Permafacture

Reputation: 410

the answer at this post is pretty well developed: Image Cropping using Python

it uses pygame as the GUI.

Upvotes: 3

jsbueno
jsbueno

Reputation: 110456

The PIL library itself provides no GUI code --what you are asking for is an application with a GUI. I'd suggest using Tkinter + PIL, but there is no way it is trivial - you will have to handle the mouse clicks, create a rectangle object tracking it, have a way to "reset" the rectangle, and so on.

Unfortunatelly the Canvas Tkinter widget which is used to draw things on is poorly documented - you will have to read trough it here: http://www.pythonware.com/library/tkinter/introduction/canvas.htm

Bellow there is an example code that reads an image file from the disk and draws it on a tkinter window. As you can see, here is some object juggling to get it right.

import Tkinter
import Image, ImageTk, ImageDraw

image_file = "svg.png"

w = Tkinter.Tk()

img = Image.open(image_file)
width, height = img.size
ca = Tkinter.Canvas(w, width=width, height=height)
ca.pack()
photoimg = ImageTk.PhotoImage("RGB", img.size)
photoimg.paste(img)
ca.create_image(width//2,height//2, image=photoimg)
Tkinter.mainloop()

Upvotes: 2

Related Questions