如何使用Python裁剪通过鼠标单击选择的区域? [英] How to crop a region selected with mouse click, using Python?
问题描述
我正在使用Matplotlib和PIL处理python,需要查看图像选择并剪切我必须使用的区域,仅保留所选区域的图像. pil(使用im.crop),但如何选择鼠标单击来裁剪图像的坐标? 为了更好地解释,我像这样裁剪图像:
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()
我需要在要使用的矩形中单击鼠标以给出坐标"crop_rectangle",我该怎么办?
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?
谢谢
推荐答案
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()
这篇关于如何使用Python裁剪通过鼠标单击选择的区域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!