如何使用 Python 裁剪通过鼠标单击选择的区域?
我正在使用 Matplotlib 和 PIL 使用 python,需要查看图像选择并剪切我必须处理的区域,只留下所选区域的图像。我已经知道如何用 pil 剪切 imagens(使用im.crop)但是我如何选择坐标来通过鼠标单击裁剪图像? 为了更好地解释,我像这样裁剪图像:
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'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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 matplotlib.widgets.RectangleSelector (感谢 Joe Kington 的建议)处理按钮按下事件:
You could use matplotlib.widgets.RectangleSelector (thanks to Joe Kington for this suggestion) to handle button press events:
你在用tk吗?这将取决于您使用的窗口管理。不过,在高级别上,您会需要类似的内容:
回调本身因窗口工具而异,但概念是相同的:捕获单击事件和释放事件,并比较触发事件的点以创建你的矩形。诀窍是记住找出它们从哪个角开始(第二个点始终与该角相对)并相对于原始图像本身创建要裁剪的矩形。
同样,根据工具的不同,您可能需要将单击事件放入图像的坐标空间中。
are you using tk? it will depend on what window management you are using. High level though, you'll want something like:
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.