开发者

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

c开发者_如何学JAVArop_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


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


are you using tk? it will depend on what window management you are using. High level though, you'll want something like:

def onMouseDown():
    // get and save your coordinates

def onMouseUp():
    // save these coordinates as well

    // now compare your coordinates to fingure out which corners
    // are being used and define your rectangle

The callbacks themselves will differ from window tool to window tool, but the concept will be the same: capture the click down event and release event and compare the points where the events were triggered to create your rectangle. The trick is to remember to figure out which corner they are starting at (the second point is always opposite that corner) and creating your rectangle to be cropped, relative to the original image itself.

Again, depending on the tool, you will probably need to put your click events in your image's coordinate space.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜