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
答案 0 :(得分:0)
您可以使用'BoundedRect'函数获取框的坐标。然后使用切片操作,提取图像的所需部分。
答案 1 :(得分:0)
我最近为我的一个项目完成了此操作,并且效果很好。
这是我在Python OpenCV中实现此技术的技术:
cv2.imshow()
函数显示图像。cv2.EVENT_LBUTTONDOWN
和cv2.EVENT_LBUTTONUP
进行此操作。您可以编写一个函数来使用鼠标捕获事件记录两个点,并将其传递给cv2.setMouseCallback()
。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)
这是我在一张图像上得到的结果之一。
在开始自己完善本教程之前,我先按照这本优秀的教程进行操作,因此可以从这里开始:Capturing mouse click events with Python and OpenCV。您还应该阅读所附教程底部的注释,以轻松改进代码。