How to crop image around box in python openCV?

时间:2019-04-16 23:11:38

标签: python opencv computer-vision

I am working on a program to crop a image around a rectangle in OpenCV. How could I go about doing this. I also need it to be able to turn multiple rectangles into cropped images.

I've tried using this tutorial: https://www.pyimagesearch.com/2016/02/08/opencv-shape-detection/, but I dont know how to get the borders of the shape and crop around it.

I hope to get an output of multiple images, that have pictures of the contents of the triangle.

Thank you in advance

2 个答案:

答案 0 :(得分:0)

您可以使用'BoundedRect'函数获取框的坐标。然后使用切片操作,提取图像的所需部分。

答案 1 :(得分:0)

我最近为我的一个项目完成了此操作,并且效果很好。

这是我在Python OpenCV中实现此技术的技术:

  • 使用OpenCV的cv2.imshow()函数显示图像。
  • 在图像上选择2个点(x,y)。这可以通过使用OpenCV捕获鼠标单击事件来完成。一种方法是,用鼠标单击第一个点所在的位置,同时仍然单击移向第二个点,并在光标位于正确的点上时从鼠标单击中释放。这将为您选择2个点。在OpenCV中,您可以使用cv2.EVENT_LBUTTONDOWNcv2.EVENT_LBUTTONUP进行此操作。您可以编写一个函数来使用鼠标捕获事件记录两个点,并将其传递给cv2.setMouseCallback()
  • 一旦有了2个坐标,就可以使用OpenCV的cv2.rectangle()函数绘制一个矩形,在其中可以传递图像,2个点以及要绘制的矩形的颜色等其他参数。
  • 一旦对这些结果感到满意,就可以使用以下方式裁剪结果:
image = cv2.imread("path_to_image")
cv2.setMouseCallback("image", your_callback_function)
cropped_img = image[points[0][1]:points[1][1], points[0][0]:points[1][0]]
cv2.imshow("Cropped Image", cropped_img)
cv2.waitKey(0)

这是我在一张图像上得到的结果之一。

之前(原始图片)before

选定的感兴趣区域并在其周围绘制一个矩形roi selected

之后(裁剪后的图像)after

在开始自己完善本教程之前,我先按照这本优秀的教程进行操作,因此可以从这里开始:Capturing mouse click events with Python and OpenCV。您还应该阅读所附教程底部的注释,以轻松改进代码。