Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm working with python using Matplotlib and PIL and a need to look into a image select and cut the area that i have to work with, leaving only the image of the selected area.I alredy know how to cut imagens with pil(using im.crop) but how can i select the coordinates to croped the image with mouse clicks? To better explain, i crop the image like this:

import Pil 
import Image
im = Image.open("test.jpg")

crop_rectangle = (50, 50, 200, 200)
cropped_im = im.crop(crop_rectangle)

cropped_im.show()

I need to give the coordinates "crop_rectangle" with the mouse click in a rectangle that i wanna work with, how can i do it?

Thank you

like image 614
Carlos Pinto da Silva Neto Avatar asked Feb 24 '23 09:02

Carlos Pinto da Silva Neto


1 Answers

You could use matplotlib.widgets.RectangleSelector (thanks to Joe Kington for this suggestion) to handle button press events:

import numpy as np
import matplotlib.pyplot as plt
import Image
import matplotlib.widgets as widgets

def onselect(eclick, erelease):
    if eclick.ydata>erelease.ydata:
        eclick.ydata,erelease.ydata=erelease.ydata,eclick.ydata
    if eclick.xdata>erelease.xdata:
        eclick.xdata,erelease.xdata=erelease.xdata,eclick.xdata
    ax.set_ylim(erelease.ydata,eclick.ydata)
    ax.set_xlim(eclick.xdata,erelease.xdata)
    fig.canvas.draw()

fig = plt.figure()
ax = fig.add_subplot(111)
filename="test.png"
im = Image.open(filename)
arr = np.asarray(im)
plt_image=plt.imshow(arr)
rs=widgets.RectangleSelector(
    ax, onselect, drawtype='box',
    rectprops = dict(facecolor='red', edgecolor = 'black', alpha=0.5, fill=True))
plt.show()
like image 153
unutbu Avatar answered Feb 26 '23 08:02

unutbu